---
title: "Control lab: simulation, margins and pole placement in Python"
heading: Writing three tools every control engineer uses, a step-response simulator for any proper transfer function, a calculator for crossover frequencies and stability margins, and Ackermann's pole-placement formula, each checked against results from the lessons
eyebrow: S9 · Lesson 50 · Control lab
xp: 60
---

::: hook
Control toolboxes hide three routines that you've used by hand all course: simulate a transfer function's step response, find a loop's crossovers and margins, and compute the state-feedback gain that puts the poles where you want them. In this lab you'll write all three in NumPy and test them against numbers you already know: the 16.3% overshoot of ζ = 0.5, the 3× gain margin of $10/(s(s + 1)(s + 5))$, and the servo gains of lesson 34.
:::

::: predict
## Your margin calculator scans the phase of $L(j\omega)$ for −180°. Why must it unwrap the phase first?

- [ ] Because NumPy returns degrees
- [x] Because the raw angle jumps from −180° to +180° exactly where you're looking for the crossing
- [ ] Because the magnitude is in decibels
- [ ] It doesn't need to

::: reveal
`np.angle` returns values in (−π, π], so a phase falling past −180° reappears just below +180°. A naive sign test sees the jump, not a smooth crossing, and a root finder lands on the discontinuity. `np.unwrap` removes the jumps over a dense grid; inside a small bracket, measure the phase relative to the bracket's end, $\angle(L(\omega)/L(\omega_k))$, to keep it continuous.
:::
:::

::: nameit
## Simulating a transfer function

For $\frac{b_0s^n + \dots + b_n}{s^n + a_1s^{n-1} + \dots + a_n}$, the controllable canonical form has $\dot{x}_1 = -a_1x_1 - \dots - a_nx_n + u$ and $\dot{x}_i = x_{i-1}$, with output $y = \sum_i(b_i - b_0a_i)x_i + b_0u$. A fixed-step RK4 integrator is accurate to about $(\omega\Delta t)^4$ per step, plenty for step responses with Δt a hundredth of the fastest time constant.

## Margins

Evaluate $L(j\omega)$ on a dense logarithmic grid, unwrap the phase, find the first sign change of $|L| - 1$ and of $\angle L + 180°$, and refine each by bisection. Report None when a crossing doesn't exist in the range.

## Ackermann's formula

$$K = \begin{pmatrix} 0 & \cdots & 0 & 1 \end{pmatrix}W_r^{-1}p_d(A), \qquad W_r = \begin{pmatrix} B & AB & \cdots & A^{n-1}B \end{pmatrix}$$

where $p_d(A)$ is the desired characteristic polynomial evaluated at the matrix A. `np.poly(poles)` gives the polynomial's coefficients from its roots.
:::

::: example
## What should `margins([10], [0.1, 1, 0])` return?

::: solution
1. **Recognize the loop.** That's $10/(s(0.1s + 1))$ from lesson 23.
2. **Gain crossover.** It crosses over at 7.8615 rad/s with 51.83° of phase margin.
3. **Phase crossover.** Its phase only approaches −180° as ω → ∞, so there's no phase crossover and no finite gain margin.

**Answer:** (7.8615, 51.83, None, None).
:::
:::

::: example
## What does `place` return for the double integrator with poles at −2 and −3?

::: solution
1. **Companion form.** The desired polynomial is $s^2 + 5s + 6$ and the double integrator's is $s^2$, so
   $$K = (6,\ 5)$$
2. **Check with Ackermann's formula.**
   $$\begin{aligned} W_r &= \begin{pmatrix} 0 & 1 \\ 1 & 0 \end{pmatrix} \\ p_d(A) &= A^2 + 5A + 6I \\ &= \begin{pmatrix} 6 & 5 \\ 0 & 6 \end{pmatrix} \end{aligned}$$
3. **Read off K.** The last row after $W_r^{-1}$ is (6, 5), the same gain.

**Answer:** K = (6, 5).
:::
:::

::: check
kind: python

## Step 1. Write `step_response(num, den, T, dt)`: the controllable canonical form integrated with RK4.

```python starter
import numpy as np

def step_response(num, den, T, dt):
    # Step response of the proper transfer function num(s)/den(s) (coefficient lists, highest power
    # first) from t = 0 to T in steps of dt. Return (t, y) as numpy arrays.
    # Hint: build the controllable canonical form and integrate it with RK4.
    t = np.arange(0, T + dt/2, dt)
    return t, np.zeros(len(t))

t, y = step_response([1], [1, 1], 5, 0.01)
print(y[-1])
```

```python solution
import numpy as np

def step_response(num, den, T, dt):
    den = np.asarray(den, float); num = np.asarray(num, float)
    a = den/den[0]; b = num/den[0]
    n = len(a) - 1
    b = np.concatenate([np.zeros(n + 1 - len(b)), b])
    d = b[0]
    c = b[1:] - d*a[1:]
    A = np.zeros((n, n)); A[0, :] = -a[1:]
    if n > 1:
        A[1:, :-1] = np.eye(n - 1)
    B = np.zeros(n); B[0] = 1.0
    f = lambda x: A @ x + B
    t = np.arange(0, T + dt/2, dt)
    x = np.zeros(n); y = np.zeros(len(t))
    for k in range(len(t)):
        y[k] = c @ x + d
        k1 = f(x); k2 = f(x + dt/2*k1); k3 = f(x + dt/2*k2); k4 = f(x + dt*k3)
        x = x + dt/6*(k1 + 2*k2 + 2*k3 + k4)
    return t, y

t, y = step_response([1], [1, 1], 5, 0.01)
print(y[-1])
```

```python tests
import numpy as np
t, y = step_response([2], [0.5, 1], 3, 0.001)
assert np.allclose(y, 2*(1 - np.exp(-t/0.5)), atol=1e-8), "The first-order step response 2/(0.5s + 1) must be 2(1 − e^(−t/0.5))."
t, y = step_response([100], [1, 10, 100], 2, 0.0005)
os = (y.max() - 1)*100
assert abs(os - 16.3034) < 0.01, f"ζ = 0.5 must overshoot 16.30%; got {os:.3f}%."
assert abs(t[np.argmax(y)] - np.pi/np.sqrt(75)) < 0.001, "The peak must come at π/ω_d."
t, y = step_response([1, 1], [1, 3, 2], 6, 0.001)
assert np.allclose(y, 0.5 - np.exp(-2*t)/2, atol=1e-7), "(s + 1)/((s + 1)(s + 2)) must step like 1/(s + 2): 0.5(1 − e^(−2t))."
t, y = step_response([1, 0], [1, 1], 4, 0.001)
assert np.allclose(y, np.exp(-t), atol=1e-7), "s/(s + 1) has a direct feedthrough: its step response is e^(−t), starting at 1."
```

::: right
Right. Your simulator matches first- and second-order closed forms, cancels a pole against a zero, and handles direct feedthrough.
:::
:::

::: check
kind: python

## Step 2. Write `margins(num, den)`: gain and phase crossovers, phase margin and gain margin.

```python starter
import numpy as np

def margins(num, den):
    # For the loop gain L(s) = num(s)/den(s), return (wc, pm, w180, gm): the gain crossover (rad/s),
    # the phase margin (degrees), the phase crossover (rad/s) and the gain margin (as a factor).
    # Use None for a crossover that doesn't exist between 1e-3 and 1e4 rad/s.
    return None, None, None, None

print(margins([10], [1, 6, 5, 0]))
```

```python solution
import numpy as np

def margins(num, den):
    L = lambda w: np.polyval(num, 1j*w)/np.polyval(den, 1j*w)
    w = np.logspace(-3, 4, 200001)
    v = L(w)
    mag = np.abs(v); ph = np.unwrap(np.angle(v))
    def refine(g, lo, hi):
        glo = g(lo)
        for _ in range(100):
            m = 0.5*(lo + hi)
            if (g(m) > 0) == (glo > 0): lo, glo = m, g(m)
            else: hi = m
        return 0.5*(lo + hi)
    wc = pm = w180 = gm = None
    i = np.where(np.diff(np.sign(mag - 1)) != 0)[0]
    if len(i):
        k = i[0]
        wc = refine(lambda x: abs(L(x)) - 1, w[k], w[k + 1])
        pm = 180 + np.degrees(ph[k] + np.angle(L(wc)/L(w[k])))
    j = np.where(np.diff(np.sign(ph + np.pi)) != 0)[0]
    if len(j):
        k = j[0]
        w180 = refine(lambda x: ph[k] + np.angle(L(x)/L(w[k])) + np.pi, w[k], w[k + 1])
        gm = 1/abs(L(w180))
    return wc, pm, w180, gm

print(margins([10], [1, 6, 5, 0]))
```

```python tests
import numpy as np
wc, pm, w180, gm = margins([10], [1, 6, 5, 0])
assert w180 is not None and abs(w180 - np.sqrt(5)) < 1e-6, f"The phase crossover of 10/(s(s+1)(s+5)) is √5 = 2.2361; got {w180}."
assert abs(gm - 3) < 1e-6, f"Its gain margin is 30/10 = 3; got {gm}."
assert abs(wc - 1.227064) < 1e-5 and abs(pm - 25.3898) < 1e-3, f"Its crossover is 1.2271 rad/s with 25.39° of margin; got {wc}, {pm}."
wc, pm, w180, gm = margins([10], [0.1, 1, 0])
assert abs(wc - 7.861514) < 1e-5 and abs(pm - 51.8273) < 1e-3, f"10/(s(0.1s + 1)) crosses at 7.8615 with 51.83°; got {wc}, {pm}."
assert w180 is None and gm is None, "A two-pole loop never reaches −180° at a finite frequency: return None for its phase crossover and gain margin."
wc, pm, w180, gm = margins([60], [1, 3, 3, 1])
assert abs(w180 - np.sqrt(3)) < 1e-6 and abs(gm - 8/60) < 1e-9, "60/(s + 1)³ is unstable: its gain margin is 8/60, below 1."
```

::: right
Right. Your margins match the lessons to the last digit, and you report None where a crossover doesn't exist.
:::
:::

::: check
kind: python

## Step 3. Write `place(A, B, poles)`: Ackermann's formula.

```python starter
import numpy as np

def place(A, B, poles):
    # Ackermann's formula: return the gain row K (a 1-D array) such that A - B K has the given poles.
    # A is n x n, B is n x 1 (or length n), poles is a list of n (possibly complex) numbers.
    return np.zeros(np.asarray(A).shape[0])

print(place([[0, 1], [0, 0]], [0, 1], [-2, -3]))
```

```python solution
import numpy as np

def place(A, B, poles):
    A = np.asarray(A, float); B = np.asarray(B, float).reshape(-1, 1)
    n = A.shape[0]
    Wr = np.hstack([np.linalg.matrix_power(A, k) @ B for k in range(n)])
    p = np.real(np.poly(poles))
    pA = sum(c*np.linalg.matrix_power(A, n - i) for i, c in enumerate(p))
    e = np.zeros(n); e[-1] = 1
    return e @ np.linalg.solve(Wr, pA)

print(place([[0, 1], [0, 0]], [0, 1], [-2, -3]))
```

```python tests
import numpy as np
K = np.asarray(place([[0, 1], [0, 0]], [0, 1], [-2, -3])).ravel()
assert np.allclose(K, [6, 5]), f"A double integrator with poles at −2 and −3 needs K = (6, 5); got {K}."
K = np.asarray(place([[0, 1], [0, -62.5]], [0, 1250], [-35 + 35.70714j, -35 - 35.70714j])).ravel()
assert np.allclose(K, [2, 0.006], atol=1e-6), f"The servo of lesson 34 needs K = (2, 0.006); got {K}."
rng = np.random.default_rng(3)
for n in (3, 4):
    A = rng.normal(size=(n, n)); B = rng.normal(size=(n, 1))
    want = np.array([-1.0, -2.0, -3.0, -4.0][:n])
    K = np.asarray(place(A, B, list(want))).ravel()
    got = np.sort(np.linalg.eigvals(A - B @ K.reshape(1, -1)).real)
    assert np.allclose(got, np.sort(want), atol=1e-6), f"For a random {n}-state system the closed-loop poles must be {np.sort(want)}; got {got}."
```

::: right
Right. Your gains place the poles exactly, for the servo of lesson 34 and for random three- and four-state systems.
:::
:::

::: explain
## Why does Ackermann's formula need the controllability matrix to be invertible?

::: model
Ackermann's formula works by transforming the system into companion form, where each feedback gain adds directly to one coefficient of the characteristic polynomial, choosing the gains there, and transforming back. The transformation is built from the controllability matrix, so it only exists when that matrix is invertible. If it isn't, some mode of the system can't be influenced by the input at all, and no choice of gains can move that mode's pole. The formula then has no solution, which is the algebraic form of the physical fact.
:::
:::

::: practice

::: check
given: K = 5 | 20 | 60; a = 1 | 2; b = 5 | 10
answer: a*b*(a + b)/K
tolerance: 0.5%

## What gain margin should `margins` report for $\given{K}/(s(s + \given{a})(s + \given{b}))$?

::: misses
- [any] $ab(a + b)/K$.
:::
:::

::: check
given: p = 1 | 4; q = 3 | 10
answer: p*q
tolerance: 0.5%

## What first gain should `place` return for a double integrator with poles −{p}, −{q}?

::: misses
- [any] $k_1 = pq$.
:::
:::

::: check
given: z = 0.3 | 0.6 | 0.8
answer: 100*exp(-pi*z/sqrt(1 - z^2))
unit: %
tolerance: 0.5%

## What overshoot should `step_response` show for ζ = {z}?

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