"""Controller tuning: PID on a first-order-plus-dead-time plant and PID/DMC control of an exothermic CSTR.
Controller tuning is a multi-objective trade-off (tracking speed, overshoot,
disturbance rejection, actuator wear, safety margins) that control engineers
judge by looking at closed-loop responses; it was the first case study of
EASY-IEC (Madár, Abonyi and Szeifert, 2005: tuning of a model predictive
controller). Both problems render the responses and report the usual
performance indicators as objectives.
"""
from __future__ import annotations
import numpy as np
from ..core.problem import Problem
from ..core.space import Box
__all__ = ["PIDTuning", "CSTRControl", "response_metrics"]
[docs]
def response_metrics(t, y, r, u, t0: float, t1: float | None = None, band: float = 0.02) -> dict:
"""IAE, overshoot (%), settling time and input total variation of a setpoint response on ``[t0, t1)``."""
m = (t >= t0) & ((t < t1) if t1 is not None else True)
tt, yy, rr, uu = t[m], y[m], r[m], u[m]
dt = t[1] - t[0]
step = rr[-1] - yy[0]
iae = float(np.sum(np.abs(rr - yy)) * dt)
if abs(step) > 1e-12:
over = float(max(0.0, (np.max((yy - yy[0]) / step) - 1) * 100))
out = np.abs(yy - rr[-1]) > band * abs(step)
ts = float(tt[np.flatnonzero(out)[-1]] - tt[0]) if out.any() else 0.0
else:
over, ts = 0.0, 0.0
return {"iae": iae, "overshoot": over, "settling_time": ts, "input_tv": float(np.sum(np.abs(np.diff(uu))))}
[docs]
class PIDTuning(Problem):
"""PID control of a first-order-plus-dead-time process :math:`G(s)=Ke^{-\\theta s}/(\\tau s+1)`.
ISA-form PID with setpoint weighting ``b``, derivative on the filtered
measurement (filter factor ``N``), input saturation and anti-windup by
conditional integration. Scenario: unit setpoint step at ``t=2`` and an
input load disturbance at ``t=50``. The default utility of a simulated
"control engineer" rewards small IAE, little overshoot and smooth control
action, scaled by the SIMC tuning of Skogestad (2003) as a reference.
"""
name = "pid"
title = "PID controller tuning"
domain = "process control"
goal = ("Choose the controllers with fast, well-damped setpoint tracking, good disturbance rejection and smooth, "
"not aggressive control action.")
description = "Each candidate shows the closed-loop output (top, with the setpoint) and the controller output (bottom)."
objective_senses = {"iae": -1, "overshoot": -1, "settling_time": -1, "input_tv": -1, "disturbance_iae": -1}
modality = "image"
def __init__(self, K: float = 1.0, tau: float = 10.0, theta: float = 3.0, dt: float = 0.1, horizon: float = 90.0,
u_limit: float = 4.0):
self.K, self.tau, self.theta, self.dt, self.horizon, self.u_limit = K, tau, theta, dt, horizon, u_limit
self.space = Box([0.05, 1.0, 0.01, 0.0, 2.0], [6.0, 60.0, 10.0, 1.0, 20.0],
names=["Kc", "Ti", "Td", "b", "N"], log=[True, True, True, False, False],
units=["", "s", "s", "", ""])
self.objective_senses = dict(self.objective_senses)
tc = theta
self.simc = np.array([tau / (K * (tc + theta)), min(tau, 4 * (tc + theta)), 0.011, 1.0, 10.0])
self._ref = None
self._ref = self.objectives(self.simc)
e = lambda i, v=1.0: np.eye(5)[i] * v # noqa: E731
self.semantic_axes = {"faster": e(0) + e(1, -0.5), "more aggressive": e(0), "calmer": e(0, -1) + e(2, -0.5),
"less overshoot": e(3, -1) + e(0, -0.3), "smoother": e(2, -1) + e(4, -0.5),
"less oscillation": e(0, -0.6) + e(1, 0.6)}
self.feature_names = ["iae", "overshoot", "settling_time", "input_tv", "disturbance_iae"]
self.descriptors = ((1, (0.0, 1.0)), (3, (0.0, 1.0)))
[docs]
def presets(self):
return {"SIMC": self.simc.copy(), "aggressive": np.array([4.0, 6.0, 1.0, 1.0, 10.0]),
"sluggish": np.array([0.3, 30.0, 0.01, 0.5, 10.0])}
def simulate(self, x):
p = self.space.decode(x)
dt = self.dt
n = int(self.horizon / dt)
t = np.arange(n) * dt
r = np.where(t >= 2.0, 1.0, 0.0)
d = np.where(t >= 50.0, -0.6, 0.0)
delay = int(round(self.theta / dt))
ubuf = np.zeros(n + delay + 1)
y = np.zeros(n)
u = np.zeros(n)
yf = 0.0
integ = 0.0
x_state = 0.0
Tf = max(p["Td"] / p["N"], dt)
yf_prev = 0.0
for k in range(n):
meas = x_state
y[k] = meas
yf = yf + dt / Tf * (meas - yf)
dterm = -p["Kc"] * p["Td"] * (yf - yf_prev) / dt
yf_prev = yf
e = r[k] - meas
v = p["Kc"] * (p["b"] * r[k] - meas) + integ + dterm
uk = float(np.clip(v, -self.u_limit, self.u_limit))
if abs(v) <= self.u_limit or np.sign(e) != np.sign(v):
integ += p["Kc"] * dt / p["Ti"] * e
u[k] = uk
ubuf[k + delay] = uk
x_state += dt / self.tau * (-x_state + self.K * (ubuf[k] + d[k]))
return t, y, r, u, d
[docs]
def objectives(self, x):
t, y, r, u, d = self.simulate(x)
m = response_metrics(t, y, r, u, 2.0, 50.0)
dist = float(np.sum(np.abs(r[t >= 50] - y[t >= 50])) * self.dt)
m["disturbance_iae"] = dist
return m
def objectives_names(self):
return list(self.objective_senses)
[docs]
def features(self, x):
o = self.objectives(x)
ref = self._ref or o
return np.array([min(o["iae"] / (3 * ref["iae"]), 1), min(o["overshoot"] / 50, 1),
min(o["settling_time"] / 48, 1), min(o["input_tv"] / (5 * max(ref["input_tv"], 1e-3)), 1),
min(o["disturbance_iae"] / (3 * ref["disturbance_iae"]), 1)])
[docs]
def utility(self, x, target=None):
if target is not None:
return super().utility(x, target)
o = self.objectives(x)
ref = self._ref
s = (np.exp(-0.5 * (o["iae"] / ref["iae"] - 1) ** 2 / 0.4) if o["iae"] > ref["iae"] else 1.0)
s *= np.exp(-o["overshoot"] / 15)
s *= np.exp(-max(o["input_tv"] / max(ref["input_tv"], 1e-3) - 1.5, 0) / 2)
s *= np.exp(-max(o["disturbance_iae"] / ref["disturbance_iae"] - 1, 0) / 1.5)
return float(s)
[docs]
def render_plot(self, x, ax):
t, y, r, u, d = self.simulate(x)
fig = ax.figure
ax.remove()
a1 = fig.add_axes([0.13, 0.42, 0.84, 0.53])
a2 = fig.add_axes([0.13, 0.08, 0.84, 0.28], sharex=a1)
a1.plot(t, r, color="#8A96A3", lw=1.2, ls="--")
a1.plot(t, y, color="#285780", lw=2.2)
a1.set_ylim(-0.3, 1.8)
a2.plot(t, u, color="#D55E00", lw=1.6)
a2.set_ylim(-self.u_limit * 1.05, self.u_limit * 1.05)
for a in (a1, a2):
a.tick_params(labelsize=6)
for s in ("top", "right"):
a.spines[s].set_visible(False)
a1.tick_params(labelbottom=False)
a1.text(0.02, 0.92, "output y", transform=a1.transAxes, fontsize=7, color="#285780")
a2.text(0.02, 0.8, "control u", transform=a2.transAxes, fontsize=7, color="#D55E00")
[docs]
def describe(self, x):
o = self.objectives(x)
p = self.space.decode(x)
return (f"PID controller Kc={p['Kc']:.3g}, Ti={p['Ti']:.3g} s, Td={p['Td']:.3g} s, b={p['b']:.2f}, N={p['N']:.1f}. "
f"Setpoint step: IAE={o['iae']:.2f}, overshoot={o['overshoot']:.1f} %, settling time={o['settling_time']:.1f} s; "
f"disturbance IAE={o['disturbance_iae']:.2f}; control-signal total variation={o['input_tv']:.2f}.")
[docs]
class CSTRControl(Problem):
"""Temperature control of an exothermic continuous stirred-tank reactor.
First-order irreversible reaction A→B with jacket cooling (the classical
benchmark model; parameter values as widely used after Seborg et al. and
Henson and Seborg, 1997: :math:`q=100` L/min, :math:`V=100` L,
:math:`C_{Af}=1` mol/L, :math:`T_f=350` K, :math:`\\rho=1000` g/L,
:math:`C_p=0.239` J/(g K), :math:`\\Delta H=-5\\cdot10^4` J/mol,
:math:`E/R=8750` K, :math:`k_0=7.2\\cdot10^{10}` 1/min,
:math:`UA=5\\cdot10^4` J/(min K)). The coolant temperature :math:`T_c`
(limited to 250–350 K) controls the reactor temperature. The operating point
(:math:`T\approx350` K, :math:`C_A\approx0.5` mol/L at :math:`T_c=300` K) is
the open-loop *unstable* middle steady state of the reactor (Jacobian
eigenvalues ≈ −0.45 and +2.83 1/min), so poor tuning leads to runaway or
extinction. Scenario: setpoint 350 → 355 K at 1 min, feed temperature +3 K
at 8 min.
``controller="pid"`` tunes a PID controller; ``controller="dmc"`` tunes an
unconstrained dynamic matrix controller (Cutler and Ramaker, 1980) that
supervises a fixed stabilizing proportional temperature loop (the usual
arrangement of MPC on top of regulatory control): prediction horizon,
control horizon, move suppression and reference-trajectory filter, the MPC
tuning task of the original EASY-IEC paper. Temperatures above 380 K are
reported as a safety violation.
"""
name = "cstr"
title = "CSTR temperature control"
domain = "process control"
goal = ("Choose the controllers that reach the new reactor temperature quickly without dangerous overshoot, "
"reject the feed disturbance and use the coolant gently.")
description = ("Each candidate shows the reactor temperature with its setpoint (top), the coolant temperature "
"(middle) and the reactant concentration (bottom).")
objective_senses = {"iae": -1, "overshoot": -1, "max_temperature": -1, "coolant_tv": -1, "disturbance_iae": -1}
q, V, CAf, Tf0, rho, Cp, dH, ER, k0, UA = 100.0, 100.0, 1.0, 350.0, 1000.0, 0.239, -5e4, 8750.0, 7.2e10, 5e4
def __init__(self, controller: str = "pid", dt: float = 0.01, horizon: float = 15.0):
self.controller = controller
self.dt = dt
self.horizon = horizon
self.Tc0 = 300.0
self.ss = self._steady(self.Tc0)
if controller == "pid":
self.space = Box([2.0, 0.1, 0.001, 0.0], [40.0, 10.0, 0.5, 1.0], names=["Kc", "Ti", "Td", "b"],
log=[True, True, True, False], units=["K/K", "min", "min", ""])
e = lambda i, v=1.0: np.eye(4)[i] * v # noqa: E731
self.semantic_axes = {"faster": e(0), "calmer": e(0, -1) + e(2, -0.5), "less overshoot": e(3, -1),
"smoother": e(2, -1)}
else:
self.space = Box([3, 1, 1e-3, 0.0], [40, 8, 10.0, 0.95], names=["P", "M", "lambda", "alpha"],
kinds=["int", "int", "real", "real"], log=[False, False, True, False])
e = lambda i, v=1.0: np.eye(4)[i] * v # noqa: E731
self.semantic_axes = {"faster": e(2, -1) + e(3, -0.5), "calmer": e(2) + e(3, 0.5),
"smoother": e(2) + e(0, 0.3)}
self._build_dmc()
self.objective_senses = dict(self.objective_senses)
self.feature_names = ["iae", "overshoot", "max_temperature", "coolant_tv", "disturbance_iae"]
self.descriptors = ((1, (0.0, 1.0)), (3, (0.0, 1.0)))
# ------------------------------------------------------------------ model
def _rhs(self, CA, T, Tc, Tf):
k = self.k0 * np.exp(-self.ER / T)
dCA = self.q / self.V * (self.CAf - CA) - k * CA
dT = (self.q / self.V * (Tf - T) + (-self.dH) / (self.rho * self.Cp) * k * CA
+ self.UA / (self.V * self.rho * self.Cp) * (Tc - T))
return dCA, dT
def _steady(self, Tc):
from scipy.optimize import fsolve
sol = fsolve(lambda v: self._rhs(v[0], v[1], Tc, self.Tf0), [0.5, 350.0])
return float(sol[0]), float(sol[1])
def _step(self, CA, T, Tc, Tf, h):
def f(c, t):
return np.array(self._rhs(c, t, Tc, Tf))
s = np.array([CA, T])
k1 = f(*s)
k2 = f(*(s + h / 2 * k1))
k3 = f(*(s + h / 2 * k2))
k4 = f(*(s + h * k3))
s = s + h / 6 * (k1 + 2 * k2 + 2 * k3 + k4)
return s[0], s[1]
Kp_inner = 5.0
def _inner(self, sp, T):
return float(np.clip(self.Tc0 + self.Kp_inner * (sp - T), 250.0, 350.0))
def _build_dmc(self, Ts: float = 0.1, n_model: int = 60):
CA, T = self.ss
sub = int(round(Ts / self.dt))
resp = []
sp = self.ss[1] + 1.0
for _ in range(n_model):
for _ in range(sub):
CA, T = self._step(CA, T, self._inner(sp, T), self.Tf0, self.dt)
resp.append(T - self.ss[1])
self.dmc_Ts = Ts
self.dmc_step = np.array(resp)
def simulate(self, x):
p = self.space.decode(x)
dt = self.dt
n = int(self.horizon / dt)
t = np.arange(n) * dt
r = np.where(t >= 1.0, 355.0, self.ss[1])
Tf = np.where(t >= 8.0, self.Tf0 + 3.0, self.Tf0)
CA, T = self.ss
Tc = self.Tc0
Y = np.zeros(n)
U = np.zeros(n)
C = np.zeros(n)
slew = 600.0 * dt
if self.controller == "pid":
integ, Tprev = 0.0, T
Tfilt = T
for k in range(n):
Y[k], C[k] = T, CA
Tfilt += dt / max(p["Td"] / 10, dt) * (T - Tfilt)
e = r[k] - T
dterm = -p["Kc"] * p["Td"] * (Tfilt - Tprev) / dt
Tprev = Tfilt
T0 = self.ss[1]
v = self.Tc0 + p["Kc"] * (p["b"] * (r[k] - T0) - (T - T0)) + integ + dterm
target = float(np.clip(v, 250, 350))
if 250 < v < 350:
integ += p["Kc"] * dt / p["Ti"] * e
Tc = Tc + np.clip(target - Tc, -slew, slew)
U[k] = Tc
CA, T = self._step(CA, T, Tc, Tf[k], dt)
else:
P, M, lam, alpha = p["P"], min(p["M"], p["P"]), p["lambda"], p["alpha"]
S = self.dmc_step
A = np.zeros((P, M))
for i in range(P):
for j in range(min(i + 1, M)):
A[i, j] = S[i - j]
Kd = np.linalg.solve(A.T @ A + lam * np.eye(M), A.T)[0]
sub = int(round(self.dmc_Ts / dt))
past_du: list[float] = []
u_dmc = self.ss[1]
Nm = len(S)
ref_f = self.ss[1]
for k in range(n):
Y[k], C[k] = T, CA
if k % sub == 0:
free = np.full(P, T - self.ss[1])
for idx, du in enumerate(reversed(past_du[-Nm:])):
lag = idx + 1
for i in range(P):
a = S[min(i + lag, Nm - 1)] - S[min(lag - 1, Nm - 1)]
free[i] += a * du
ref_f = r[k]
traj = np.array([(alpha ** (i + 1)) * (T - ref_f) + ref_f for i in range(P)]) - self.ss[1]
du = float(Kd @ (traj - free))
u_new = float(np.clip(u_dmc + du, 330, 380))
past_du.append(u_new - u_dmc)
u_dmc = u_new
Tc = Tc + np.clip(self._inner(u_dmc, T) - Tc, -slew, slew)
U[k] = Tc
CA, T = self._step(CA, T, Tc, Tf[k], dt)
if not np.isfinite(T) or T > 600:
Y[k + 1:] = 600.0
U[k + 1:] = Tc
C[k + 1:] = CA
break
return t, Y, r, U, C
[docs]
def objectives(self, x):
t, Y, r, U, C = self.simulate(x)
m = response_metrics(t, Y, r, U, 1.0, 8.0)
m["max_temperature"] = float(np.max(Y))
m["coolant_tv"] = float(np.sum(np.abs(np.diff(U))))
m.pop("input_tv")
m["disturbance_iae"] = float(np.sum(np.abs(r[t >= 8] - Y[t >= 8])) * self.dt)
m["safety_violation"] = float(np.max(Y) > 380.0)
return m
def objectives_names(self):
return list(self.objective_senses)
[docs]
def features(self, x):
o = self.objectives(x)
return np.array([min(o["iae"] / 10, 1), min(o["overshoot"] / 100, 1), np.clip((o["max_temperature"] - 355) / 25, 0, 1),
min(o["coolant_tv"] / 400, 1), min(o["disturbance_iae"] / 5, 1)])
[docs]
def utility(self, x, target=None):
if target is not None:
return super().utility(x, target)
o = self.objectives(x)
if o["safety_violation"]:
return 0.0
if self.controller == "pid":
s = np.exp(-o["iae"] / 2.0) * np.exp(-o["overshoot"] / 30.0) * np.exp(-o["coolant_tv"] / 400.0)
s *= np.exp(-o["disturbance_iae"] / 1.0)
else:
# the DMC supervises a stabilizing inner loop, so every tuning is fairly good; the scales measure the
# excess over what good tunings achieve (IAE 0.6 K·min, coolant variation 48.5 K, disturbance IAE 0.075)
s = np.exp(-max(o["iae"] - 0.6, 0) / 0.6) * np.exp(-o["overshoot"] / 10.0)
s *= np.exp(-max(o["coolant_tv"] - 48.5, 0) / 20.0) * np.exp(-max(o["disturbance_iae"] - 0.075, 0) / 0.15)
return float(np.clip(s, 0, 1))
[docs]
def render_plot(self, x, ax):
t, Y, r, U, C = self.simulate(x)
fig = ax.figure
ax.remove()
a1 = fig.add_axes([0.15, 0.55, 0.82, 0.42])
a2 = fig.add_axes([0.15, 0.30, 0.82, 0.2], sharex=a1)
a3 = fig.add_axes([0.15, 0.06, 0.82, 0.2], sharex=a1)
a1.plot(t, r, color="#8A96A3", lw=1.2, ls="--")
a1.plot(t, Y, color="#285780", lw=2.2)
a1.axhline(380, color="#D55E00", lw=0.8, ls=":")
a1.set_ylim(340, 385)
a2.plot(t, U, color="#D55E00", lw=1.6)
a2.set_ylim(245, 355)
a3.plot(t, C, color="#009E73", lw=1.6)
a3.set_ylim(0, 1)
for a, lab in ((a1, "T [K]"), (a2, "Tc [K]"), (a3, "CA [mol/L]")):
a.tick_params(labelsize=6)
for s in ("top", "right"):
a.spines[s].set_visible(False)
a.text(0.01, 0.82, lab, transform=a.transAxes, fontsize=6.5)
a1.tick_params(labelbottom=False)
a2.tick_params(labelbottom=False)
[docs]
def describe(self, x):
o = self.objectives(x)
p = self.space.decode(x)
par = ", ".join(f"{k}={v:.3g}" for k, v in p.items())
return (f"{self.controller.upper()} controller ({par}). Setpoint 350→355 K: IAE={o['iae']:.2f} K·min, "
f"overshoot={o['overshoot']:.1f} %, settling={o['settling_time']:.2f} min, peak T={o['max_temperature']:.1f} K"
f"{' (SAFETY LIMIT EXCEEDED)' if o['safety_violation'] else ''}; disturbance IAE={o['disturbance_iae']:.2f}; "
f"coolant total variation={o['coolant_tv']:.1f} K.")