PID controller tuning¶
A PID controller keeps a process at its set point: a temperature, a speed, a level. It measures the output y, computes the error e between the set point and y, and sets the control signal u from three terms: proportional to the error (gain Kp), to its integral (Ki), and to its rate of change (Kd). Tuning means choosing the three gains.
Here the plant is three equal first order lags in a row, with transfer function 1 / (s + 1)^3, a standard test case. The goal is a fast and accurate response to a unit step of the set point, measured by the ITAE (the integral of time times the absolute error), under two limits:
- the output may overshoot the set point by at most 5 percent,
- the control signal must stay within +-10, the range of the actuator.
The classic Ziegler and Nichols rule gives Kp = 4.8, Ki = 2.65 and Kd = 2.18 for this plant, with an ITAE of 5.54 and 54 percent overshoot. There is no published optimum for this exact setting, so the rule is the reference.
The model¶
The variable is the three gains, one Real vector between 0 and 20. The objective simulates the closed loop with small time steps and returns the ITAE and the two limits as inequality constraints (g <= 0). It is vectorized: it simulates a whole population of controllers at once, one row each, which is much faster than one at a time. Gains that make the loop unstable give a huge ITAE, or an infinite one when the simulation overflows, so the algorithms drop them.
The derivative acts on the measured output instead of the error, a common choice in practice: a step of the set point then does not cause a spike in the control signal.
import numpy as np
import ypea
dt = 0.01 # simulation time step (s)
times = np.arange(0, 20 + dt, dt)
# the plant 1 / (s + 1)^3 as x' = A x + B u, with output y = x3
A = np.array([
[-1.0, 0.0, 0.0],
[1.0, -1.0, 0.0],
[0.0, 1.0, -1.0],
])
B = np.array([1.0, 0.0, 0.0])
def simulate(kp, ki, kd):
"""Step responses of a batch of PID controllers, one row per controller."""
n = len(kp)
x = np.zeros((n, 3)) # plant states
integral = np.zeros(n)
outputs = np.zeros((n, len(times)))
controls = np.zeros((n, len(times)))
for k in range(len(times)):
y = x[:, 2]
error = 1.0 - y # the set point is 1
slope = x[:, 1] - x[:, 2] # dy/dt of this plant
u = kp * error + ki * integral - kd * slope
outputs[:, k] = y
controls[:, k] = u
integral = integral + error * dt
x = x + dt * (x @ A.T + u[:, None] * B)
return outputs, controls
def tuning_objective(sol):
kp = sol.gains[:, 0]
ki = sol.gains[:, 1]
kd = sol.gains[:, 2]
with np.errstate(all="ignore"): # unstable gains may overflow: their value is then infinite
y, u = simulate(kp, ki, kd)
itae = np.sum(times * np.abs(1.0 - y), axis=1) * dt
overshoot = np.max(y, axis=1) - 1.0
largest_control = np.max(np.abs(u), axis=1)
limits = np.column_stack([
overshoot - 0.05, # at most 5 percent overshoot
largest_control - 10.0, # the actuator gives at most +-10
])
return itae, limits
problem = ypea.Problem(
ypea.Real("gains", shape=3, lb=0, ub=20),
tuning_objective,
vectorized=True,
name="PID",
)
result = ypea.LSHADE(max_nfe=3_000).solve(problem, seed=1)
print(result.summary())
print("Kp, Ki, Kd:", result.best.solution.gains.round(3))
L-SHADE on PID
best objective value: 0.805132
feasible: True (violation 0)
evaluations: 3000, iterations: 155, time: 2.75 s, stopped by: max_nfe
Kp, Ki, Kd: [9.987 0.999 7.289]
Differs from Python: MATLAB draws its own random numbers, so the results differ from Python's. The objective returns ITAE and the limits as two outputs (outputs=2).
dt = 0.01; % simulation time step (s)
times = 0:dt:20;
% the plant 1 / (s + 1)^3 as x' = A x + B u, with output y = x3
A = [
-1.0 0.0 0.0
1.0 -1.0 0.0
0.0 1.0 -1.0
];
B = [1.0 0.0 0.0];
problem = ypea.Problem( ...
vars=ypea.Real("gains", shape=3, lb=0, ub=20), ...
objective=@(sol) tuning_objective(sol.gains, A, B, times, dt), ...
outputs=2, ...
vectorized=true, ...
name="PID");
result = ypea.LSHADE(max_nfe=3000).solve(problem, seed=1);
disp(result.summary())
fprintf("Kp, Ki, Kd: %s\n", mat2str(round(result.best.solution.gains, 3)))
function [itae, limits] = tuning_objective(gains, A, B, times, dt)
kp = gains(:, 1);
ki = gains(:, 2);
kd = gains(:, 3);
% unstable gains may overflow: their value is then infinite or NaN
[y, u] = simulate(kp, ki, kd, A, B, times, dt);
itae = sum(times .* abs(1.0 - y), 2) * dt;
overshoot = max(y, [], 2) - 1.0;
largest_control = max(abs(u), [], 2);
limits = [
overshoot - 0.05, ... % at most 5 percent overshoot
largest_control - 10.0 % the actuator gives at most +-10
];
end
function [outputs, controls] = simulate(kp, ki, kd, A, B, times, dt)
% Step responses of a batch of PID controllers, one row per controller.
n = numel(kp);
x = zeros(n, 3); % plant states
integral = zeros(n, 1);
outputs = zeros(n, numel(times));
controls = zeros(n, numel(times));
for k = 1:numel(times)
y = x(:, 3);
err = 1.0 - y; % the set point is 1
slope = x(:, 2) - x(:, 3); % dy/dt of this plant
u = kp .* err + ki .* integral - kd .* slope;
outputs(:, k) = y;
controls(:, k) = u;
integral = integral + err * dt;
x = x + dt * (x * A' + u * B);
end
end
L-SHADE on PID
best objective value: 0.805132
feasible: true (violation 0)
evaluations: 3000, iterations: 155, time: 1.47 s, stopped by: max_nfe
Kp, Ki, Kd: [9.987 0.999 7.288]
The tuned controller has an ITAE of 0.805, about 7 times lower than the Ziegler and Nichols rule, and meets both limits. The full script, examples/applications/pid_tuning.py, also plots the responses.
Results¶
Five algorithms for continuous problems, each with 10 seeded runs of 3000 evaluations:
| Algorithm | Best | Mean | Worst | Feasible runs |
|---|---|---|---|---|
| DE | 0.8102 | 0.8248 | 0.8412 | 10 of 10 |
| PSO | 0.8179 | 0.8364 | 0.8808 | 10 of 10 |
| GA | 0.8067 | 0.8186 | 0.8315 | 10 of 10 |
| CMA-ES | 0.8051 | 0.8051 | 0.8051 | 10 of 10 |
| L-SHADE | 0.8051 | 0.8051 | 0.8051 | 10 of 10 |
CMA-ES and L-SHADE find the same best gains in every run. DE, GA and PSO stay within 10 percent of them with this small budget. With only three variables, a smooth objective and an expensive simulation, CMA-ES is a good first choice for tuning problems like this one.
Try it on your own plant¶
Replace A and B with a state space model of your plant, and slope with the derivative of its output (for a model with output y = C x and C B = 0, that is x @ (C @ A)). Choose dt well below the fastest time constant of the loop. Here a 10 times smaller step changes the best ITAE by about 2 percent. Other goals work the same way, for example the ISE (squared error) or the settling time, and with two goals at once a multi-objective algorithm gives the whole trade-off.