Below you’ll find a compact, end-to-end example that
- Reads a closed-loop data log (time, set-point, controller output, process value).
- Verifies the PID algorithm that produced the controller output (sanity check).
- Identifies an open-loop process model 𝐺p(z) between the controller output u (k) and the process value y (k), using a simple, transparent ARX fit.
- Optionally converts that discrete model to a continuous transfer function so you can simulate or do classical loop analysis.
Everything is written in Python/NumPy/SciPy so it runs anywhere; an equivalent MATLAB snippet is appended at the very end.
Python implementation
import numpy as np
from numpy.linalg import lstsq
from scipy import signal, optimize
import matplotlib.pyplot as plt
# --------------------------------------------------------------------------
# 1) LOAD / PREPARE THE CLOSED-LOOP DATA
# --------------------------------------------------------------------------
# Replace this with your own log-file import
data = np.loadtxt("pid_log.csv", delimiter=",", skiprows=1)
t = data[:, 0] # time [s]
sp = data[:, 1] # set-point
u = data[:, 2] # controller output (manipulated variable)
y = data[:, 3] # process (measured) value
Ts = np.mean(np.diff(t)) # sampling period, assumes uniform
# --------------------------------------------------------------------------
# 2) (OPTIONAL) VERIFY THE PID ALGORITHM
# --------------------------------------------------------------------------
# Known PID parameters (parallel / ideal form)
Kp = 2.0
Ki = 0.5 # 1/s
Kd = 0.1 # s
Nd = 10 # derivative filter coefficient (if you use one)
# Discrete PID (Tustin) –– matches most PLC/DCS implementations
def pid_discrete(e, Ts, Kp, Ki, Kd, Nd=10):
"""Return complete control signal u(k) given the error trace e(k)."""
# Pre-allocate
N = len(e)
up, ui, ud, u = np.zeros(N), np.zeros(N), np.zeros(N), np.zeros(N)
# Tustin derivative filter variables
ad = Nd * Ts / (1 + Nd * Ts)
bd = Kd * Nd / (1 + Nd * Ts)
for k in range(1, N):
up[k] = Kp * e[k]
ui[k] = ui[k-1] + Ki*Ts*e[k]
# filtered derivative
ud[k] = ad*ud[k-1] + bd*(e[k] - e[k-1])
u[k] = up[k] + ui[k] + ud[k]
return u
e = sp - y # control error
u_hat = pid_discrete(e, Ts, Kp, Ki, Kd, Nd) # predicted control action
print(f"PID verification RMS error = {np.std(u - u_hat):.4f}")
# Inspect visually
plt.figure(); plt.plot(t, u, t, u_hat, '--')
plt.legend(['logged u', 're-built u']); plt.show()
# If the RMS error is small, the assumed PID form is correct – good!
# --------------------------------------------------------------------------
# 3) IDENTIFY OPEN-LOOP PLANT y = Gp(z) · u
# --------------------------------------------------------------------------
# A very common, transparent choice is an ARX(n_a, n_b, n_k) model.
# n_a : # of past y terms ; n_b : # of past u terms ; n_k : input delay
na, nb, nk = 2, 2, 1 # a 2nd-order, 1-sample-delay plant is a good start
# Build regression matrix Φ θ = Y (standard least squares)
N = len(y)
max_lag = max(na, nb+nk-1)
Phi, Yvec = [], []
for k in range(max_lag, N):
# ‑y(k-1)…-y(k-na)
Phi.extend([[-y[k-i] for i in range(1, na+1)] +
[ u[k-i] for i in range(nk, nk+nb)]])
Yvec.append(y[k])
Phi = np.asarray(Phi)
Yvec = np.asarray(Yvec)
theta, *_ = lstsq(Phi, Yvec, rcond=None) # θ = [a1..a_na , b1..b_nb]
a_coeffs = np.concatenate(([1.0], theta[:na])) # denominator
b_coeffs = theta[na:] # numerator
# Discrete Transfer Function Gp(z) = B(z^{-1}) / A(z^{-1})
Gp_d = signal.dlti(b_coeffs, a_coeffs, dt=Ts)
print(f"Discrete plant numerator : {b_coeffs}")
print(f"Discrete plant denominator: {a_coeffs}")
# --------------------------------------------------------------------------
# 4) VALIDATE THE MODEL
# --------------------------------------------------------------------------
t_sim, y_sim, _ = signal.dlsim(Gp_d, u, t=t) # simulate with same input
plt.figure()
plt.plot(t, y, label='Measured PV')
plt.plot(t, y_sim, '--', label='Model output')
plt.legend(); plt.title('Open-loop model validation'); plt.show()
# --------------------------------------------------------------------------
# 5) (OPTIONAL) CONTINUOUS APPROXIMATION FOR CLASSICAL ANALYSIS
# --------------------------------------------------------------------------
# Bilinear (Tustin) transform to continuous s-domain
Gp_c = signal.cont2discrete(Gp_d.to_ss(), Ts, method='bilinear', alpha=0.5)[0]
# Or simply use "control.matlab" if you prefer
How the pieces fit together
• Closed-loop log → error e(k) and control signal u(k) are correlated,
but because we measured u(k) directly, we can treat it as the excitation input.
Identification methods (ARX, IV-ARX, PEM, sub-space) work, albeit with a bit more bias than with open-loop data. For quick tuning or digital-twin creation this bias is usually acceptable.
• The PID verification step is purely a sanity check. If the reconstructed u_hat
largely overlaps the logged u, you know the gains and the discrete formula you are using match what the controller actually did. Otherwise you’re trying to identify a moving target (bad).
• ARX is chosen because it is transparent and comes with zero external
dependencies. If you need a higher-fidelity model, swap
the ARX section with a sysid library of your choice (N4SID, PEM, OE, BJ, …).
MATLAB / Octave (same idea, 10 lines)
load pid_log.mat % t, sp, u, y
Ts = mean(diff(t));
data_id = iddata(y, u, Ts);
na = 2; nb = 2; nk = 1;
model = arx(data_id, [na nb nk]); % open-loop plant
figure
compare(data_id, model) % validation plot
tf(model) % continuous/discrete form
Frequently asked tweaks
- Non-integer dead-time: use OE/BJ structures or
procest / tfest in MATLAB ('P2D', 'P3D', …).
- Noise or disturbances: add an AR (noise) model or use IV-ARX to remove bias.
- Controller output saturation or rate limits: segment the data to keep only portions where the actuator is not saturated; otherwise the identification sees a nonlinear system.
Enjoy building and playing with your open-loop model!