Designing controllers in Python
About this lesson
Design a controller for a mass on a spring and a damper using nothing but plain Python. Store the plant as lists of coefficients, close the loop with list arithmetic, simulate a step with the Runge-Kutta method, find the poles, and measure overshoot and settling time. Then let a for loop search for the gains and check the winner with the python-control library. The P, PI, PD and PID ideas themselves are taught in the lessons "Adding integral and derivative action" and "The PID controller".
The plant as two lists
Our plant is a 1 kg mass on a 20 N/m spring and a 10 N·s/m damper. Its transfer function is 1/(s² + 10s + 20). Python stores it as two lists of coefficients: [1] on top, [1, 10, 20] below.
# a transfer function is two lists of coefficients # G(s) = 1 / (s² + 10 s + 20): m = 1, b = 10, k = 20 G = [1], [1, 10, 20] print(G[0][-1] / G[1][-1]) # 0.05
Read the lesson step by step
The plant as two lists
Our plant is a 1 kg mass on a 20 N/m spring and a 10 N·s/m damper. Its transfer function is 1/(s² + 10s + 20). Python stores it as two lists of coefficients: [1] on top, [1, 10, 20] below.
# a transfer function is two lists of coefficients # G(s) = 1 / (s² + 10 s + 20): m = 1, b = 10, k = 20 G = [1], [1, 10, 20] print(G[0][-1] / G[1][-1]) # 0.05Simulate a step
Python cannot read a curve off a formula, so it marches time forward in 1 ms steps with the Runge-Kutta method. Push the mass with 1 N and it creeps to just 0.05 m. We want 1 m: we need a controller.
# march time forward: controllable canonical form + RK4 def step(num, den, T=2.0, dt=0.001): n = len(den) - 1 a = [c / den[0] for c in den[1:]] b = [0.0] * (n - len(num)) + [c / den[0] for c in num] f = lambda x: x[1:] + [1.0 - sum(a[n - 1 - i] * x[i] for i in range(n))] x, t, y = [0.0] * n, [], [] for k in range(round(T / dt) + 1): t.append(k * dt) y.append(sum(b[n - 1 - i] * x[i] for i in range(n))) k1 = f(x) k2 = f([xi + dt / 2 * ki for xi, ki in zip(x, k1)]) k3 = f([xi + dt / 2 * ki for xi, ki in zip(x, k2)]) k4 = f([xi + dt * ki for xi, ki in zip(x, k3)]) x = [xi + dt / 6 * (p + 2 * q + 2 * r + s) for xi, p, q, r, s in zip(x, k1, k2, k3, k4)] return t, y t, y = step(*G) # a 1 N push, plant alone print(round(y[-1], 2)) # 0.05Close the loop in code
Add a proportional controller, Kp = 300, and feed the position back. Closing the loop is list arithmetic: T = CG / (1 + CG). Multiplying and adding the coefficient lists gives T(s) = 300 / (s² + 10s + 320).
# polynomials as lists: multiply and add def mul(p, q): r = [0.0] * (len(p) + len(q) - 1) for i, pi in enumerate(p): for j, qj in enumerate(q): r[i + j] += pi * qj return r def add(p, q): n = max(len(p), len(q)) p, q = [0] * (n - len(p)) + p, [0] * (n - len(q)) + q return [x + y for x, y in zip(p, q)] def pid(Kp, Ki=0, Kd=0): # (Kd s² + Kp s + Ki) / s if Ki: return [Kd, Kp, Ki], [1, 0] return ([Kd, Kp] if Kd else [Kp]), [1] def close(C, G): # T = CG / (1 + CG) num = mul(C[0], G[0]) return num, add(mul(C[1], G[1]), num) T = close(pid(300), G) print(T) # ([300.0], [1.0, 10.0, 320.0])Measure the response
Step the closed loop, then read numbers off the samples. It overshoots by 40.1 %, settles within 2 % after 0.77 s and ends at 0.94 m, not 1. Proportional control alone leaves a steady-state error.
# overshoot %, 2 % settling time, final value def info(t, y, T): yf = T[0][-1] / T[1][-1] # final value = DC gain over = max(0.0, (max(y) - yf) / yf * 100) ts = next(t[i + 1] for i in range(len(y) - 1, -1, -1) if abs(y[i] - yf) > 0.02 * abs(yf)) return round(over, 1), round(ts, 2), round(yf, 2) t, y = step(*T) print(info(t, y, T)) # (40.1, 0.77, 0.94)The poles explain it
A root finder gives the closed-loop poles: -5 ± j17.18. They sit far from the real axis, so the damping ratio is only 0.28. Light damping means a big overshoot.
# roots of the denominator (Durand-Kerner) def poles(den): a = [c / den[0] for c in den] n = len(a) - 1 z = [(0.4 + 0.9j) ** k for k in range(n)] for _ in range(500): new = [] for i, zi in enumerate(z): v = 0 for c in a: v = v * zi + c d = 1 for j, zj in enumerate(z): if j != i: d *= zi - zj new.append(zi - v / d) z = new z.sort(key=lambda p: (p.real, p.imag)) return [round(p.real, 2) if abs(p.imag) < 1e-9 else complex(round(p.real, 2), round(p.imag, 2)) for p in z] print(poles(T[1])) # [(-5-17.18j), (-5+17.18j)]Add derivative action
Derivative action (Kd = 10) pushes against fast motion. The poles move to -10 ± j14.83, the overshoot falls to 15.3 % and the loop settles in 0.29 s. It still ends at 0.94 m.
T = close(pid(300, 0, 10), G) # Kp = 300, Kd = 10 t, y = step(*T) print(info(t, y, T), poles(T[1])) # (15.3, 0.29, 0.94) [(-10-14.83j), (-10+14.83j)]Add integral action
Integral action adds up the error over time and keeps pushing until it is zero. With Kp = 350, Ki = 300 and Kd = 50 the output heads for exactly 1 m, with no overshoot, settling in 0.83 s.
T = close(pid(350, 300, 50), G) # Kp, Ki, Kd t, y = step(*T) print(info(t, y, T), poles(T[1])) # (0.0, 0.83, 1.0) [-53.14, -5.9, -0.96]Let a loop search
Now Python does the trying. A for loop steps Kd from 0 to 80 and keeps the fastest design with under 5 % overshoot. It picks Kd = 20: 4.1 % overshoot, settled in 0.73 s, faster than Kd = 50.
# let a loop try the designs: Kd = 0, 10, ..., 80 best = None for Kd in range(0, 81, 10): T = close(pid(350, 300, Kd), G) t, y = step(*T) over, ts, yf = info(t, y, T) if over < 5 and (best is None or ts < best[2]): best = (Kd, over, ts) print(best) # (20, 4.1, 0.73)Check with python-control
The python-control library does the same jobs with tf, feedback and step_info. It reports 4.1 % and 0.73 s for the winner, matching our code. Give it the time grid: its own default stopped one loop at 0.13 s.
# the same design with python-control (pip install control) import control as ct import numpy as np G = ct.tf([1], [1, 10, 20]) C = ct.tf([20, 350, 300], [1, 0]) # Kd s² + Kp s + Ki over s T = ct.feedback(C * G, 1) t = np.linspace(0, 2, 2001) # give it the time grid i = ct.step_info(T, T=t) print(round(i['Overshoot'], 1), round(i['SettlingTime'], 2)) # 4.1 0.73The design loop
Every design went round one loop: model, simulate, measure, change the gains. Python makes each lap take milliseconds, so you can try many controllers, then check the winner with a trusted library and on the real machine.
# the design loop, in four lines of the script # model G = [1], [1, 10, 20] # design T = close(pid(Kp, Ki, Kd), G) # simulate t, y = step(*T) # measure info(t, y, T) and poles(T[1]) # ...change the gains and go round again # overshoot settling final # P 40.1 % 0.77 s 0.94 # PD 15.3 % 0.29 s 0.94 # PID 0.0 % 0.83 s 1.00 # Kd = 20 4.1 % 0.73 s 1.00
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01In Python, G = [1], [1, 10, 20]. Which transfer function is that?
The first list is the numerator and the second the denominator, highest power of s first: 1 / (s² + 10s + 20).
02With C = 300 and G = 1/(s² + 10s + 20), what is the closed-loop T = CG / (1 + CG)?
Numerator: 300 × 1. Denominator: (s² + 10s + 20) + 300. Adding the coefficient lists [1, 10, 20] and [300] (padded to [0, 0, 300]) gives [1, 10, 320].
03The P design settles at 0.94 m instead of 1 m. Which change makes the final value exactly 1?
Integral action puts a pole at s = 0 in the controller, so the closed-loop DC gain becomes Ki / Ki = 1. A bigger Kp only shrinks the error (Kp / (20 + Kp)); derivative action does not change the DC gain at all.
04The P loop's poles are -5 ± j17.18. Why does it overshoot by 40.1 %?
The damping ratio is ζ = 5 / √(5² + 17.18²) ≈ 0.28. A low damping ratio means a large overshoot. The poles are in the left half-plane, so the loop is stable.
05python-control's step_info returned a settling time of nan for a loop that clearly settles. What is the most likely fix?
The automatic time grid can be too short: in python-control 0.10.2 it stopped the Kd = 50 loop at 0.13 s. With T = linspace(0, 2, 2001) the library returns 0.83 s, the same as our own code.
Glossary
- Transfer function
- The ratio of the Laplace transforms of output and input, Y(s)/U(s), for a linear system starting at rest. In code it is two lists of polynomial coefficients.
- Unity feedback
- A loop that feeds the output straight back to be subtracted from the reference. Its closed-loop transfer function is T = CG / (1 + CG).
- Runge-Kutta (RK4)
- A method that moves a differential equation forward one small time step at a time, using four slope estimates per step. It is far more accurate than a single Euler step of the same size.
- Percent overshoot
- How far the peak goes past the final value, as a percentage of that final value.
- Settling time (2 %)
- The time after which the response stays within 2 % of its final value.
- Pole
- A root of the closed-loop denominator. Where the poles sit decides how fast the response is and how much it rings.
- Damping ratio ζ
- For a pair of complex poles −σ ± jω, ζ = σ / √(σ² + ω²). A small ζ means light damping and a large overshoot.
- python-control
- An open-source Python library for control design. tf builds a transfer function, feedback closes a loop, step_info measures a step response.
Notes and sources
- The mass-spring-damper and the P, PD and PID gains are the worked example of the PID tutorial in the Control Tutorials for MATLAB (University of Michigan and Carnegie Mellon). Here every curve and number is recomputed in plain Python.
- step() writes T(s) in controllable canonical form (one first-order equation per power of s) and integrates it with the classical fourth-order Runge-Kutta method. With 1 ms steps the result matches python-control to every digit shown.
- The PID loop has a slow pole at -0.96 sitting next to a zero at −1 (the numerator 50s² + 350s + 300 = 50(s + 1)(s + 6)). They nearly cancel, so the response creeps the last 0.7 % to 1 m; at 2 s it reads 0.994 m.
- In python-control 0.10.2, step_info(T) with no time grid chose one ending at 0.13 s for the Kd = 50 loop and reported a settling time of nan. Passing T = linspace(0, 2, 2001) gives 0.83 s, the same as our code.
- Percent overshoot is how far the peak passes the final value, as a percentage of it. The 2 % settling time is when the response enters, and stays inside, a band 2 % either side of the final value.
- N. S. Nise, Control Systems Engineering, 8th ed., Wiley (ch. 4 time response, ch. 5 block diagrams)
- K. Ogata, Modern Control Engineering, 5th ed., Pearson (PID control; controllable canonical form)
- G. F. Franklin, J. D. Powell, A. Emami-Naeini, Feedback Control of Dynamic Systems, 8th ed., Pearson
- MIT OpenCourseWare 16.06 Principles of Automatic Control (S. Hall)
- MIT OpenCourseWare 6.302 Feedback Systems (Roberge, Dawson, Lundberg)
- Control Tutorials for MATLAB (University of Michigan, Carnegie Mellon): PID tutorial, the mass-spring-damper example
- python-control documentation: step_info
- python-control documentation: feedback
- Durand-Kerner method (root finding used by poles())
Quiz Unlocks after the last step.