---
title: "Lab: driven systems in code"
heading: Frequency response, convolution and partial fractions by computer
eyebrow: A8 · Lesson 34 · Lab: driven systems
xp: 60
---

::: hook
Lessons 26 to 33 gave three ways to find a driven system's response: phasors for the steady state, convolution with the impulse response for any input, and Laplace transforms with partial fractions for the whole solution. Each is a few lines of NumPy. In this lab you'll sweep a resonator's frequency response and find its peak, check the phasor prediction against a long simulation, convolve an impulse response with a pulse, and invert a Laplace transform from the roots of its denominator.
:::

::: play
- The curve is the gain $|H(j\omega)|$ of $\ddot y + 2\zeta\dot y + y = u$, a resonator with $\omega_0$ = 1 rad/s.
- Lower $\zeta$ and the peak grows taller and narrower, and moves toward $\omega_0$.
- Above $\zeta = 0.707$ there's no peak at all: the gain falls steadily from 1.
:::

```sim plot
view: graph
x: w = 0..3 rad/s
y: gain = 0..6
slider: z = 0.05..1 step 0.01 = 0.2
plot: 1/sqrt((1 - w^2)^2 + (2*z*w)^2) | label: |H(jω)| | samples: 600
readout: peak frequency, rad/s = sqrt(1 - 2*z^2)*step(0.7071 - z) | digits: 4
readout: gain at ω₀ = 1/(2*z) | digits: 4
```

::: predict
## A resonator with $\zeta$ = 0.1 is driven at exactly $\omega_0$. How large is its steady-state response compared with its response to a constant input of the same size?

- [ ] The same
- [ ] Twice
- [x] Five times
- [ ] Ten times

::: reveal
Five times. At $\omega = \omega_0$, $|H| = \frac{1}{2\zeta} = 5$, the quality factor $Q$. The true peak is a little higher and slightly below $\omega_0$: $\frac{1}{2\zeta\sqrt{1 - \zeta^2}} = 5.03$ at $\omega_0\sqrt{1 - 2\zeta^2} = 0.99\omega_0$.
:::
:::

::: nameit
## Frequency response

For $\ddot y + 2\zeta\omega_0\dot y + \omega_0^2y = \omega_0^2u$, replacing $\frac{d}{dt}$ by $j\omega$ gives

$$H(j\omega) = \frac{\omega_0^2}{\omega_0^2 - \omega^2 + 2j\zeta\omega_0\omega}$$

Computing it on a grid of $\omega$ with NumPy's complex arithmetic gives the gain and phase everywhere at once. For $\zeta < \frac{1}{\sqrt2}$ the gain peaks at $\omega_0\sqrt{1 - 2\zeta^2}$ with height $\frac{1}{2\zeta\sqrt{1 - \zeta^2}}$.

## Convolution on a grid

With samples every $\Delta t$, the integral $\int_0^th(\tau)x(t - \tau)\,d\tau$ becomes `np.convolve(h, x)[:n] * dt`. The error is proportional to $\Delta t$ for this simple rule.

## Partial fractions from roots

For $Y(s) = \frac{N(s)}{D(s)}$ with distinct roots $p_k$ of $D$, the residue at each root is $r_k = \frac{N(p_k)}{D'(p_k)}$, and

$$y(t) = \sum_kr_ke^{p_kt}$$

`np.roots` finds the $p_k$ and `np.polyder` gives $D'$. Complex roots come in conjugate pairs whose terms add to a real decaying sinusoid.
:::

::: example
## Find the peak of $|H(j\omega)|$ for $\zeta$ = 0.2 and $\omega_0$ = 1 rad/s.

::: solution
1. **Peak frequency.**
   $$\begin{aligned} \omega_p &= \sqrt{1 - 2(0.04)} \\ &= \sqrt{0.92} \\ &= 0.959\ \text{rad/s} \end{aligned}$$
2. **Peak height.**
   $$\begin{aligned} &\frac{1}{2(0.2)\sqrt{0.96}} \\ &= 2.55 \end{aligned}$$
3. **Check by sweep.** A sweep over 300 000 points finds the same, 0.9592 rad/s and 2.5516.
4. **Compare with $\omega_0$.** At $\omega_0$ itself the gain is $\frac{1}{0.4} = 2.5$, so the peak is only 2% higher: for light damping the distinction rarely matters.

**Answer:** the peak is 2.55, at 0.959 rad/s.
:::
:::

::: example
## Find the step response of $H(s) = \frac{1}{s^2 + 3s + 2}$ by residues.

::: solution
1. **Output transform.**
   $$Y(s) = \frac{1}{s(s^2 + 3s + 2)}$$
   so $D(s) = s^3 + 3s^2 + 2s$, with roots 0, $-1$ and $-2$.
2. **Derivative of the denominator.**
   $$D'(s) = 3s^2 + 6s + 2$$
3. **Residues.** They are $\frac{1}{D'(0)} = \frac12$, $\frac{1}{D'(-1)} = -1$ and $\frac{1}{D'(-2)} = \frac12$:
   $$y = \tfrac12 - e^{-t} + \tfrac12e^{-2t}$$
4. **Evaluate at $t = 1$.**
   $$\begin{aligned} y(1) &= 0.5 - 0.368 + 0.068 \\ &= 0.200 \end{aligned}$$

**Answer:** $y = \tfrac12 - e^{-t} + \tfrac12e^{-2t}$, which is 0.200 at $t = 1$.
:::
:::

::: check
given: z = 0.1 | 0.2 | 0.3
answer: sqrt(1 - 2*z^2)
unit: rad/s
tolerance: 0.5%

## At what frequency does the gain of a resonator with $\omega_0$ = 1 rad/s and $\zeta$ = {z} peak?

::: right
Right. $\omega_0\sqrt{1 - 2\zeta^2}$ = {answer}.
:::

::: misses
- [1] Close, but damping moves the peak slightly below $\omega_0$.
- [sqrt(1 - z^2)] That's the free ringing frequency $\omega_d$; the forced peak is at $\sqrt{1 - 2\zeta^2}$.
- [any] Not yet. Maximize $|H|$, or minimize $(1 - \omega^2)^2 + (2\zeta\omega)^2$.
:::
:::

::: check
given: a = 1 | 3; b = 2 | 5
answer: 1/(b - a)
tolerance: 0.5%

## $Y(s) = \frac{1}{(s + \given{a})(s + \given{b})}$. What is the residue at $s = -\given{a}$?

::: right
Right. Cover up $s + a$ and evaluate $\frac{1}{s + b}$ at $s = -a$: $\frac{1}{b - a}$ = {answer}.
:::

::: misses
- [1/(a - b)] That's the residue at $s = -b$.
- [any] Not yet. Cover up $s + a$ and set $s = -a$.
:::
:::

::: check
kind: python
given: z = 0.1 | 0.2 | 0.3

## Compute $|H(j\omega)| = \frac{1}{|1 - \omega^2 + 2j\zeta\omega|}$ on a grid of 300 001 points from 0.01 to 3 rad/s for $\zeta$ = {z}. Set `w_peak` and `H_peak` to the location and height of the maximum.

```python starter
import numpy as np

w_peak = H_peak = 1.0
print(w_peak, H_peak)
```

```python solution
import numpy as np

w = np.linspace(0.01, 3, 300001)
H = 1 / np.abs(1 - w**2 + 2j * z * w)
k = np.argmax(H)
w_peak, H_peak = w[k], H[k]
print(w_peak, H_peak)
```

```python tests
import math
assert abs(w_peak - math.sqrt(1 - 2 * z * z)) < 1e-4, f"The peak should be at sqrt(1 - 2 zeta^2) = {math.sqrt(1 - 2 * z * z):.5f}; got {w_peak}."
assert abs(H_peak - 1 / (2 * z * math.sqrt(1 - z * z))) < 1e-6, f"Its height should be 1/(2 zeta sqrt(1 - zeta^2)); got {H_peak}."
```

::: right
Right. A dense grid and `argmax` find the peak without any calculus, and agree with the formula.
:::
:::

::: check
kind: python

## Simulate $\ddot y + 0.4\dot y + y = \cos 0.8t$ from rest with RK4 ($h$ = 0.001) to $t$ = 200 s. Set `amp` to the largest $|y|$ over the last 50 s, and `phasor` to $\frac{1}{|1 - 0.8^2 + 0.4 \cdot 0.8j|}$.

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

```python solution
import math

def f(t, y, v):
    return v, math.cos(0.8 * t) - 0.4 * v - y

t, y, v, h, amp = 0.0, 0.0, 0.0, 0.001, 0.0
for n in range(200000):
    k1 = f(t, y, v)
    k2 = f(t + h / 2, y + h / 2 * k1[0], v + h / 2 * k1[1])
    k3 = f(t + h / 2, y + h / 2 * k2[0], v + h / 2 * k2[1])
    k4 = f(t + h, y + h * k3[0], v + h * k3[1])
    y += 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])
    t += h
    if t > 150:
        amp = max(amp, abs(y))
phasor = 1 / abs(1 - 0.8**2 + 0.4 * 0.8j)
print(amp, phasor)
```

```python tests
assert abs(phasor - 2.0761370) < 1e-6, f"The phasor amplitude is 2.07614; got {phasor}."
assert abs(amp - phasor) < 1e-4, f"Once the transient has died, the simulation should match the phasor amplitude; got {amp}."
```

::: right
Right. After 150 s the transient, decaying as $e^{-0.2t}$, is down by $e^{-30}$, and only the phasor's steady state is left.
:::
:::

::: check
kind: python

## The impulse response of $\dot y + y = x$ is $h = e^{-t}$. On a grid with $\Delta t$ = 0.001 out to $t$ = 3, convolve it with a unit pulse lasting from 0 to 1, and set `y2` to the result at $t$ = 2.

```python starter
import numpy as np

y2 = 0.0
print(y2)
```

```python solution
import numpy as np

dt = 0.001
t = np.arange(0, 3, dt)
h = np.exp(-t)
x = (t < 1).astype(float)
y = np.convolve(h, x)[:len(t)] * dt
y2 = y[int(round(2 / dt))]
print(y2)
```

```python tests
import math
exact = (math.e - 1) * math.exp(-2)
assert abs(y2 - exact) < 2e-3, f"The convolution should be close to (e - 1)e^-2 = {exact:.4f}; got {y2:.5f}."
```

::: right
Right. The sum differs from the integral by about $\Delta t$, which is why a finer grid, or the trapezoid rule, tightens it.
:::
:::

::: check
kind: python

## Write `step_response(den, t)` returning $y(t)$ for $Y(s) = \frac{1}{s \cdot \text{den}(s)}$, by residues at the roots of $s \cdot \text{den}(s)$ (assume they're distinct). `den` is a coefficient list like `[1, 3, 2]`. Set `y1 = step_response([1, 3, 2], 1.0)`.

```python starter
import numpy as np

def step_response(den, t):
    return 0.0

y1 = step_response([1, 3, 2], 1.0)
print(y1)
```

```python solution
import numpy as np

def step_response(den, t):
    D = np.polymul(den, [1, 0])
    dD = np.polyder(D)
    y = 0
    for p in np.roots(D):
        y += np.exp(p * t) / np.polyval(dD, p)
    return float(np.real(y))

y1 = step_response([1, 3, 2], 1.0)
print(y1)
```

```python tests
import math
assert abs(y1 - (0.5 - math.exp(-1) + 0.5 * math.exp(-2))) < 1e-12, f"y(1) = 0.5 - e^-1 + 0.5 e^-2 = 0.19979; got {y1}."
w = 2.0; z = 0.3
want = 1 - math.exp(-z * w * 1) * (math.cos(w * math.sqrt(1 - z * z)) + z / math.sqrt(1 - z * z) * math.sin(w * math.sqrt(1 - z * z)))
assert abs(step_response([1 / w**2, 2 * z / w, 1], 1.0) - want) < 1e-9, "Complex poles should work too: an underdamped resonator's step response."
```

::: right
Right. Root finding plus one derivative replaces the whole partial-fraction calculation, complex poles included.
:::
:::

::: check
kind: python
given: z = 0.3 | 0.5 | 0.9

## Find the $-3$ dB bandwidth of $H = \frac{1}{1 - \omega^2 + 2j\zeta\omega}$ ($\zeta$ = {z}) by bisecting $|H(j\omega)| = \frac{1}{\sqrt2}$ on $[0.01, 10]$ (60 steps), and set `w_bw`.

```python starter
w_bw = 1.0
print(w_bw)
```

```python solution
import math

def gain(w):
    return 1 / abs(1 - w * w + 2j * z * w)

lo, hi = 0.01, 10.0
for _ in range(60):
    mid = (lo + hi) / 2
    if gain(mid) > 1 / math.sqrt(2):
        lo = mid
    else:
        hi = mid
w_bw = (lo + hi) / 2
print(w_bw)
```

```python tests
import math
want = math.sqrt(1 - 2 * z * z + math.sqrt(4 * z**4 - 4 * z * z + 2))
assert abs(w_bw - want) < 1e-9, f"The bandwidth is {want:.6f} rad/s; got {w_bw}."
```

::: right
Right. Bisection finds where the gain falls through 0.707, matching the closed form $\omega_0\sqrt{1 - 2\zeta^2 + \sqrt{4\zeta^4 - 4\zeta^2 + 2}}$.
:::
:::

::: explain
## A simulation and the phasor method give the same steady-state amplitude. When would you trust only the simulation?

::: model
The phasor method assumes the system is linear, time-invariant and driven by a single sinusoid, and it gives only the final steady state. Inside those assumptions it's exact and instant, and a simulation can only approach it, after the transient dies and with a small enough step. Outside them, only simulation works: a nonlinear part (a diode, a saturating amplifier, a magnetic core) generates harmonics and makes the response depend on amplitude; an input that switches or isn't periodic has no single phasor; and if you need the start-up transient, the overshoot when a source turns on, the phasor method says nothing about it. Agreement between the two in the linear case is the check that makes the simulation trustworthy in the others.
:::
:::

::: practice

::: check
given: z = 0.01..0.7
answer: sqrt(1 - 2*z^2)
tolerance: 0.5%

## Peak frequency for $\omega_0$ = 1 and $\zeta$ = {z}?

::: misses
- [any] $\sqrt{1 - 2\zeta^2}$.
:::
:::

::: check
given: z = 0.01..0.7
answer: 1/(2*z*sqrt(1 - z^2))
tolerance: 0.5%

## Peak gain for $\zeta$ = {z}?

::: misses
- [any] $\frac{1}{2\zeta\sqrt{1 - \zeta^2}}$.
:::
:::
:::
