---
title: "Frequency-response lab: Nyquist, sensitivity and delay"
heading: Evaluating loop transfer functions on the imaginary axis, counting Nyquist encirclements by phase unwrapping, finding the sensitivity peak, and computing the delay margin
eyebrow: S9 · Lesson 31 · Frequency-response lab
xp: 60
---

::: hook
Lessons 23 to 30 read stability and robustness off frequency responses: the Nyquist plot's encirclements, the margins, the sensitivity peak, how much delay a loop can swallow. Those plots are drawn by computers, and the numbers behind them come from a few simple routines: evaluate L(jω), track its phase without losing whole turns, search for peaks and crossings. In this lab you'll write them and check each against a result you can derive by hand.
:::

::: play
- The curve is $20\log|S(j\omega)|$ for the loop $L = K/(s + 1)^3$, with K on the slider.
- Below crossover |S| is small; near crossover it peaks, and the peak grows sharply as K approaches 8, the gain at which the Nyquist plot passes through −1.
- Above K = 8 the plot encircles −1 twice and the closed loop has two unstable poles, though |S| itself shows only a finite bump.
:::

```sim plot
view: graph
x: w = 0.01..100 log
y: S = -40..20 dB
slider: K = 0.5..7.9 = 4
plot: 20*log(sqrt((1 - 3*w^2)^2 + (3*w - w^3)^2)/sqrt((1 - 3*w^2 + K)^2 + (3*w - w^3)^2)) | label: |S|
```

::: predict
## How many times does the Nyquist plot of $L = 10/(s + 1)^3$ encircle −1?

- [ ] Zero
- [ ] Once
- [x] Twice, clockwise
- [ ] Three times

::: reveal
The plot crosses the negative real axis at $-K/8 = -1.25$ (at ω = √3), so −1 lies inside the loop. Following ω from −∞ to ∞ the curve goes around it twice clockwise, and with no open-loop poles in the right half-plane, Z = N + P = 2 closed-loop poles are unstable. Your encirclement counter must find this from the phase of 1 + L alone.
:::
:::

::: nameit
## What the lab computes

- **L(jω)** for $L = N(s)/D(s)$ given as coefficient lists, by Horner's rule on $s = j\omega$.
- **Encirclements** of −1: the net number of turns of $1 + L(j\omega)$ around the origin as ω runs from −∞ to ∞, counted clockwise. For a stable, strictly proper L with real coefficients, the negative-frequency half mirrors the positive one, so it's twice the unwrapped phase change from ω ≈ 0 to ω → ∞, divided by −2π. Unwrapping means adding or subtracting 2π whenever consecutive samples jump by more than π.
- **Sensitivity peak** $M_s = \max_\omega 1/|1 + L(j\omega)|$ on a dense logarithmic grid.
- **Delay margin**: find the crossover $\omega_c$ where |L| = 1 by bisection in log ω, then PM/ω_c with PM in radians.
:::

::: check
kind: python

## Write `freq_resp(num, den, w)`: L(jω) for coefficient lists (highest power first), and `bode_point(num, den, w)`: its magnitude in dB and phase in degrees (principal value).

```python starter
def freq_resp(num, den, w):
    return 1 + 0j

def bode_point(num, den, w):
    return 0.0, 0.0
```

```python solution
import cmath, math

def polyval(c, s):
    v = 0j
    for a in c:
        v = v * s + a
    return v

def freq_resp(num, den, w):
    s = 1j * w
    return polyval(num, s) / polyval(den, s)

def bode_point(num, den, w):
    v = freq_resp(num, den, w)
    return 20 * math.log10(abs(v)), math.degrees(cmath.phase(v))
```

```python tests
import math
m, p = bode_point([10], [0.1, 1, 0], 10)
assert abs(m - 20 * math.log10(10 / (10 * math.sqrt(2)))) < 1e-9 and abs(p + 135) < 1e-9, "10/(s(0.1s + 1)) at its corner: −3 dB and −135°."
assert abs(freq_resp([1], [1, 1], 0) - 1) < 1e-15, "DC gain 1."
```

::: right
Right. Horner's rule evaluates any polynomial with one multiply and one add per coefficient.
:::
:::

::: check
kind: python

## Write `encirclements(num, den)`: the net clockwise encirclements of −1 by the Nyquist plot of a stable, strictly proper L, by unwrapping the phase of 1 + L(jω) on 20 000 log-spaced frequencies from 10⁻⁴ to 10⁴ rad/s and doubling for the negative frequencies. Return a rounded integer.

```python starter
def encirclements(num, den):
    return 0
```

```python solution
import cmath, math

def polyval(c, s):
    v = 0j
    for a in c:
        v = v * s + a
    return v

def encirclements(num, den):
    total, prev = 0.0, None
    for k in range(20000):
        w = 1e-4 * 10 ** (8 * k / 19999)
        s = 1j * w
        a = cmath.phase(1 + polyval(num, s) / polyval(den, s))
        if prev is not None:
            d = a - prev
            while d > math.pi:
                d -= 2 * math.pi
            while d < -math.pi:
                d += 2 * math.pi
            total += d
        prev = a
    return round(-2 * total / (2 * math.pi))
```

```python tests
den = [1, 3, 3, 1]
assert encirclements([4], den) == 0, "K = 4: no encirclement."
assert encirclements([10], den) == 2, "K = 10: two clockwise encirclements."
assert encirclements([7.9], den) == 0 and encirclements([8.1], den) == 2, "The change happens at K = 8."
```

::: right
Right. The count changes only when the curve passes through −1, which is exactly when a closed-loop pole crosses the imaginary axis.
:::
:::

::: check
kind: python

## Write `peak_sensitivity(num, den)`: $M_s$ on 20 000 log-spaced frequencies from 10⁻³ to 10³ rad/s.

```python starter
def peak_sensitivity(num, den):
    return 1.0
```

```python solution
def polyval(c, s):
    v = 0j
    for a in c:
        v = v * s + a
    return v

def peak_sensitivity(num, den):
    best = 0.0
    for k in range(20000):
        s = 1j * 1e-3 * 10 ** (6 * k / 19999)
        best = max(best, 1 / abs(1 + polyval(num, s) / polyval(den, s)))
    return best
```

```python tests
Ms = peak_sensitivity([1], [1, 1, 0])
assert abs(Ms - 1.4679) < 1e-3, "1/(s(s + 1)): M_s = 1.468."
assert peak_sensitivity([4], [1, 3, 3, 1]) > peak_sensitivity([2], [1, 3, 3, 1]), "More gain toward instability, a higher peak."
```

::: right
Right. $M_s$ = 1.47 guarantees a gain margin of at least 3.1 and a phase margin of about 40°, whatever the loop's other details.
:::
:::

::: check
kind: python

## Write `delay_margin(num, den)`: find the gain crossover by bisection on log ω between 10⁻⁴ and 10⁴ (assume |L| falls through 1 once), then return PM/ω_c in seconds, with the phase taken in (−360°, 0].

```python starter
def delay_margin(num, den):
    return 0.0
```

```python solution
import cmath, math

def polyval(c, s):
    v = 0j
    for a in c:
        v = v * s + a
    return v

def delay_margin(num, den):
    L = lambda w: polyval(num, 1j * w) / polyval(den, 1j * w)
    lo, hi = math.log(1e-4), math.log(1e4)
    for _ in range(200):
        mid = (lo + hi) / 2
        if abs(L(math.exp(mid))) > 1:
            lo = mid
        else:
            hi = mid
    wc = math.exp(lo)
    ph = cmath.phase(L(wc))
    if ph > 0:
        ph -= 2 * math.pi
    pm = math.pi + ph
    return pm / wc
```

```python tests
import math
K, t = 10.0, 0.1
wc = math.sqrt((-1 + math.sqrt(1 + 4 * K * K * t * t)) / (2 * t * t))
want = (math.pi / 2 - math.atan(t * wc)) / wc
assert abs(delay_margin([K], [t, 1, 0]) - want) < 1e-9, "10/(s(0.1s + 1)): 0.1151 s."
assert abs(delay_margin([2], [1, 0]) - math.pi / 4) < 1e-9, "2/s: π/2 at 2 rad/s, π/4 s."
```

::: right
Right. A delay costs phase in proportion to frequency, so the margin in seconds is the phase margin spent at the crossover rate.
:::
:::

::: explain
## Why must a Nyquist encirclement count unwrap the phase rather than just look at where the plot ends?

::: model
The Nyquist plot starts and ends at known points, so its endpoints say nothing about how many times it went around −1 on the way. The count is the net number of full turns the vector from −1 to the curve makes, which is the total change of its angle divided by 2π. A computed angle is only known up to whole turns, jumping by 2π whenever it crosses the branch cut, so the code must follow it continuously from sample to sample, adding or subtracting 2π at each jump, and sample finely enough that the true angle never changes by more than half a turn between neighboring frequencies.
:::
:::
