---
title: "Lab: Laplace transforms and Bode plots in code"
heading: Poles, Bode plots, margins and responses by computer
eyebrow: A10 · Lesson 25 · Lab: Laplace and Bode in code
xp: 60
---

::: hook
Lessons 18 to 24 described systems by their transfer functions: poles and zeros, Bode plots, impulse and step responses. A transfer function is just two polynomials, and NumPy handles polynomials directly. In this lab you'll compute a Bode plot and read a feedback loop's crossover and phase margin from it, measure how far the straight-line asymptotes miss, find an RLC filter's poles and damping from its polynomial, invert a transform with complex poles and check it by simulation, and compute a pulse response by convolution.
:::

::: play
- The curves are the gain in dB of $H(s) = \frac{K}{(s + 10)(s + 100)}$ against $\log_{10}\omega$, and its straight-line asymptotes.
- Raise $K$: the curve moves up and crosses 0 dB at a higher frequency, where the two poles have used up more phase.
- The readout gives the phase margin at the crossover, which falls as $K$ rises: more gain means a less damped closed loop.
:::

```sim plot
view: graph
x: lw = 0..4
y: dB = -60..60
slider: K = 1000..100000 = 10000 log
plot: 20*log(K) - 10*log(10^(2*lw) + 100) - 10*log(10^(2*lw) + 10000) | label: |H| in dB | samples: 600
plot: 20*log(K) - 20*log(10)*step(1 - lw) - 20*lw*step(lw - 1) - 40*step(2 - lw) - 20*lw*step(lw - 2) | dashed | color: ch2 | label: asymptotes | samples: 600
plot: 0 | color: ch3 | label: 0 dB
readout: crossover, rad/s = sqrt((-10100 + sqrt(10100^2 + 4*(K^2 - 1000000)))/2) | digits: 4
readout: phase margin, degrees = 180 - (atan(sqrt((-10100 + sqrt(10100^2 + 4*(K^2 - 1000000)))/2)/10) + atan(sqrt((-10100 + sqrt(10100^2 + 4*(K^2 - 1000000)))/2)/100))*180/pi | digits: 4
```

::: predict
## At a single pole's corner frequency, how far below the straight-line asymptotes is the true gain?

- [ ] 0 dB
- [ ] 1 dB
- [x] 3 dB
- [ ] 6 dB

::: reveal
3 dB: $|H| = \frac{1}{\sqrt2}$ at the corner, or $-3.01$ dB, while both asymptotes meet at 0 dB there. An octave away, the error is about 1 dB, and a decade away it's under 0.05 dB. The asymptotes are a sketch; computing the curve takes one line.
:::
:::

::: nameit
## Transfer functions as polynomials

Store numerator and denominator coefficients highest power first: $\frac{s + 3}{s^2 + 3s + 2}$ is `num = [1, 3]`, `den = [1, 3, 2]`. Then:
- `np.polyval(num, s) / np.polyval(den, s)` evaluates $H(s)$ at any complex $s$, so $H(j\omega)$ on a frequency grid gives the Bode plot;
- `np.roots(den)` gives the poles, and `np.roots(num)` the zeros;
- residues $\frac{N(p)}{D'(p)}$ at each simple pole give the impulse response $\sum r_ke^{p_kt}$.

## Margins

For a loop gain $L(s)$, the **gain crossover** is where $|L(j\omega)| = 1$; the **phase margin** is $180°$ plus the phase there. A phase margin of 45° to 60° gives a well-damped closed loop; near 0° it rings and nearly oscillates.

## Second-order poles

$s^2 + 2\zeta\omega_0s + \omega_0^2$ has poles at $-\zeta\omega_0 \pm j\omega_0\sqrt{1 - \zeta^2}$. From computed poles: $\omega_0 = |p|$ and $\zeta = -\frac{\text{Re}\,p}{|p|}$.
:::

::: example
## Find the gain crossover and phase margin of $L(s) = \dfrac{10\,000}{(s + 10)(s + 100)}$.

::: solution
1. **Set the gain to 1.** $|L(j\omega)| = 1$ means
   $$(\omega^2 + 100)(\omega^2 + 10\,000) = 10^8$$
2. **Solve for the crossover.** That's a quadratic in $\omega^2$, with root $\omega^2 = 6108$, so
   $$\omega_c = 78.2\ \text{rad/s}$$
3. **The phase there.**
   $$\begin{aligned} \phi &= -\tan^{-1}7.82 - \tan^{-1}0.782 \\ &= -82.7° - 38.0° \\ &= -120.7° \end{aligned}$$
4. **The phase margin.**
   $$180° - 120.7° = 59.3°$$
   a comfortable loop.

**Answer:** the gain crossover is at 78.2 rad/s, and the phase margin is 59.3°.
:::
:::

::: example
## A series RLC has $R$ = 100 Ω, $L$ = 10 mH and $C$ = 1 µF, with the output across $C$. Find its poles, $\omega_0$ and $\zeta$.

::: solution
1. **The transfer function.**
   $$H = \frac{1}{LCs^2 + RCs + 1}$$
2. **Normalize the denominator.** Dividing by $LC$ gives
   $$s^2 + 10^4s + 10^8$$
3. **The poles.** Its roots are $-5000 \pm j8660$ s⁻¹, at distance $10^4$ from the origin.
4. **The natural frequency.** It's that distance:
   $$\omega_0 = 10^4\ \text{rad/s}$$
5. **The damping ratio.**
   $$\begin{aligned} \zeta &= \frac{5000}{10\,000} \\ &= 0.5 \end{aligned}$$
6. **The overshoot.** The step response overshoots by
   $$e^{-\pi \times 0.5/0.866} = 16\%$$

**Answer:** poles at $-5000 \pm j8660$ s⁻¹, $\omega_0 = 10^4$ rad/s and $\zeta = 0.5$; the step response overshoots by 16%.
:::
:::

::: check
given: f = 0.5 | 1 | 2
answer: -10*log(1 + f^2)
unit: dB
tolerance: 0.5%

## A single pole $\frac{1}{1 + s/\omega_c}$. What is its exact gain at {f} times its corner frequency?

::: right
Right. $-10\log_{10}(1 + f^2)$ = {answer}.
:::

::: misses
- [-20*log(f)] That's the asymptote; the exact curve is $-10\log_{10}(1 + f^2)$.
- [any] Not yet. $|H| = \frac{1}{\sqrt{1 + f^2}}$.
:::
:::

::: check
given: R = 50 | 100 | 150; L = 10 | 20
answer: R/2*sqrt(1e-6/(L*1e-3))
tolerance: 0.5%

## A series RLC with $R$ = {R} Ω, $L$ = {L} mH and $C$ = 1 µF. Computing its poles $p$, what is $-\text{Re}\,p/|p|$?

::: right
Right. That's $\zeta = \frac R2\sqrt{C/L}$ = {answer}.
:::

::: misses
- [any] Not yet. $\zeta = \frac{R}{2}\sqrt{\frac CL}$, which is $-\frac{\text{Re}\,p}{|p|}$ for complex poles.
:::
:::

::: check
kind: python

## For $L(s) = \frac{10\,000}{(s + 10)(s + 100)}$, compute $|L(j\omega)|$ and its phase on 200 001 log-spaced points from 1 to 10 000 rad/s. Set `wc` to the frequency where the gain is closest to 1 and `pm` to the phase margin there, in degrees.

```python starter
import numpy as np

wc = pm = 0.0
print(wc, pm)
```

```python solution
import numpy as np

num = [10000]
den = np.polymul([1, 10], [1, 100])
w = np.logspace(0, 4, 200001)
L = np.polyval(num, 1j * w) / np.polyval(den, 1j * w)
k = np.argmin(np.abs(np.abs(L) - 1))
wc = w[k]
pm = 180 + np.degrees(np.angle(L[k]))
print(wc, pm)
```

```python tests
assert abs(wc - 78.154) < 0.01, f"The crossover is 78.15 rad/s; got {wc}."
assert abs(pm - 59.28) < 0.05, f"The phase margin is 59.3 degrees; got {pm}."
```

::: right
Right. 78.2 rad/s and 59.3°, read off the computed curve exactly as you would off a plotted one.
:::
:::

::: check
kind: python

## For a single pole $\frac{1}{1 + j\omega}$, set `err1` and `err2` to the exact gain minus the asymptote, in dB, at $\omega$ = 1 and 2 (the asymptote is 0 dB below the corner and $-20\log_{10}\omega$ above).

```python starter
import numpy as np

err1 = err2 = 0.0
print(err1, err2)
```

```python solution
import numpy as np

def exact(w):
    return 20 * np.log10(1 / abs(1 + 1j * w))

def asym(w):
    return 0.0 if w <= 1 else -20 * np.log10(w)

err1 = exact(1.0) - asym(1.0)
err2 = exact(2.0) - asym(2.0)
print(err1, err2)
```

```python tests
assert abs(err1 + 3.0103) < 1e-4, f"At the corner the curve is 3.01 dB below the asymptotes; got {err1}."
assert abs(err2 + 0.9691) < 1e-4, f"An octave above, the error is 0.97 dB; got {err2}."
```

::: right
Right. 3 dB at the corner and about 1 dB an octave away: the corrections to remember when sketching.
:::
:::

::: check
kind: python

## For the RLC with $R$ = 100 Ω, $L$ = 10 mH, $C$ = 1 µF (output across $C$), find the poles of $LCs^2 + RCs + 1$ with `np.roots` and set `w0` and `zeta` from them.

```python starter
import numpy as np

w0 = zeta = 0.0
print(w0, zeta)
```

```python solution
import numpy as np

R, L, C = 100, 10e-3, 1e-6
p = np.roots([L * C, R * C, 1])[0]
w0 = abs(p)
zeta = -p.real / abs(p)
print(w0, zeta)
```

```python tests
assert abs(w0 - 1e4) < 1e-6 and abs(zeta - 0.5) < 1e-9, f"The poles give w0 = 10^4 rad/s and zeta = 0.5; got {w0}, {zeta}."
```

::: right
Right. The poles' distance from the origin is $\omega_0$, and the cosine of their angle from the negative real axis is $\zeta$.
:::
:::

::: check
kind: python

## Invert $Y(s) = \frac{5}{s(s^2 + 2s + 5)}$ by residues at the roots of its denominator (they include a complex pair) and set `y1` to $y(1)$. Then simulate $\ddot y + 2\dot y + 5y = 5$ from rest with RK4 ($h$ = 0.001) and set `y1_sim`.

```python starter
import numpy as np

y1 = y1_sim = 0.0
print(y1, y1_sim)
```

```python solution
import numpy as np

D = [1, 2, 5, 0]
dD = np.polyder(D)
y1 = float(np.real(sum(5 / np.polyval(dD, p) * np.exp(p * 1.0) for p in np.roots(D))))

def f(y, v):
    return v, 5 - 2 * v - 5 * y

y, v, h = 0.0, 0.0, 0.001
for _ in range(1000):
    k1 = f(y, v)
    k2 = f(y + h / 2 * k1[0], v + h / 2 * k1[1])
    k3 = f(y + h / 2 * k2[0], v + h / 2 * k2[1])
    k4 = f(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])
y1_sim = y
print(y1, y1_sim)
```

```python tests
import math
want = 1 - math.exp(-1) * (math.cos(2) + 0.5 * math.sin(2))
assert abs(y1 - want) < 1e-12, f"y(1) = 1 - e^-1 (cos 2 + 0.5 sin 2) = {want:.6f}; got {y1}."
assert abs(y1_sim - want) < 1e-9, f"The simulation should agree; got {y1_sim}."
```

::: right
Right. The complex residues come in a conjugate pair whose sum is real: a decaying sinusoid around the final value.
:::
:::

::: check
kind: python

## An RC low-pass with $\tau$ = 1 ms gets a 1 V pulse lasting 2 ms. Convolve its impulse response $h = \frac1\tau e^{-t/\tau}$ with the pulse on a grid of $\Delta t$ = 0.001 ms out to 6 ms, and set `v2` and `v4` to the output at 2 and 4 ms.

```python starter
import numpy as np

v2 = v4 = 0.0
print(v2, v4)
```

```python solution
import numpy as np

dt = 0.001
t = np.arange(0, 6, dt)
h = np.exp(-t)
x = (t < 2).astype(float)
v = np.convolve(h, x)[:len(t)] * dt
v2, v4 = v[2000], v[4000]
print(v2, v4)
```

```python tests
import math
assert abs(v2 - (1 - math.exp(-2))) < 2e-3, f"At the pulse's end the output is 1 - e^-2 = 0.865; got {v2}."
assert abs(v4 - (1 - math.exp(-2)) * math.exp(-2)) < 2e-3, f"Two time constants later it has decayed to 0.117; got {v4}."
```

::: right
Right. The same answers as lesson 24's step-difference method, from a single convolution that would work for any input shape.
:::
:::

::: explain
## Why is a phase margin of about 60° considered safe for a feedback loop, and what goes wrong as it shrinks?

::: model
At the crossover frequency the loop gain has magnitude 1, so the phase margin measures how far the loop is from the condition $L = -1$, where a signal would come back around the loop with the same size and inverted sign and sustain itself: oscillation. With a 60° margin, the closed loop behaves roughly like a second-order system with $\zeta$ around 0.6, a small overshoot and quick settling. As the margin shrinks, the closed-loop poles move toward the imaginary axis: overshoot and ringing grow, the response near the crossover peaks, and any drift in component values that adds phase or gain can push the loop over into oscillation. That's why margins are specified, not just stability.
:::
:::

::: practice

::: check
given: f = 0.1..10
answer: -10*log(1 + f^2)
tolerance: 0.5%

## Exact single-pole gain in dB at {f} times the corner?

::: misses
- [any] $-10\log_{10}(1 + f^2)$.
:::
:::

::: check
given: R = 10..200; L = 1..100
answer: R/2*sqrt(1e-6/(L*1e-3))
tolerance: 0.5%

## $\zeta$ of a series RLC with {R} Ω, {L} mH and 1 µF?

::: misses
- [any] $\frac R2\sqrt{C/L}$.
:::
:::
:::
