PID versus linear MPC: one simulated axis Thomas Thelliez — locally checked 3 December 2026 RUN (Python 3.9+, standard library only; locally executed with CPython 3.13.5) python3 pid_mpc_demo.py --self-test python3 pid_mpc_demo.py --output-dir demo-output python3 pid_mpc_demo.py --input demo-output/scenario.csv --output-dir replay-output The generated scenario is deterministic; it contains no random noise or seed. You can download scenario.csv instead and pass it with --input. Replay mode never overwrites that input CSV. Existing results.csv, metrics.json and response.svg in the output directory are replaced on repeat runs. COMMON PLANT AND INFORMATION Position p (m), velocity v (m/s), acceleration command u (m/s^2). Initial p=v=0. Sample interval dt=0.1 s; 180 held-input intervals, 18 s. p_next = p + dt*v + 0.5*dt^2*(u+d) v_next = v + dt*(u+d) These are exact double-integrator equations for constant acceleration over one interval, not a forward-Euler approximation. Both controllers see exact current p, v and reference r. No sensor noise, filtering delay, future setpoint preview or disturbance feedforward. Both command the same actuator interval -1 <= u <= 1 m/s^2. External acceleration d is added AFTER the actuator command. Consequently total acceleration u+d need not be within the actuator-command bounds. Reference: 0 m at 0-1 s, +1 m at 1-7 s, -0.5 m at 7-13 s, +0.5 m at 13-18 s. Unmeasured disturbance: +0.25 m/s^2 at 9 <= t < 11 s, zero otherwise. scenario.csv columns: time_s (start of interval), reference_m, disturbance_m_s2. Both reference and disturbance are held over the interval. PID IMPLEMENTATION AND TUNING Gains Kp=4, Ki=0.5, Kd=3, applied to SI-valued signals. u_raw = Kp*(r-p) + integral_contribution - Kd*v. Integral candidate = old contribution + Ki*dt*(r-p). Freeze this candidate when it would push farther into output saturation; otherwise accept it. Then clip u_raw to [-1,+1]. Derivative is on measured velocity, not on changes in reference (so no derivative kick at a step). Fixed illustrative gains, not a gain search or a claim of optimal tuning. Ignoring integral action and saturation, the chosen PD gains give the continuous nominal polynomial s^2+3s+4: natural frequency 2 rad/s and damping ratio 0.75. Integral action is deliberately modest. This is only a tuning rationale; it is not a proof for the sampled saturated PID. MPC IMPLEMENTATION AND TUNING Horizon N=20 steps = 2 seconds. It holds the CURRENT reference constant in its predictions and assumes d=0. Prediction and control horizons coincide. Minimize sum i=1..20: 8*(p_i-r)^2 + 1*v_i^2 + 0.2*u_(i-1)^2 subject to nominal plant dynamics, current initial state, and |u_j| <= 1. No additional terminal cost/set, state/velocity bound, move-rate bound, integral state or disturbance estimator. Positions, velocities and inputs enter the cost in the units above; the numerical weights depend on those units. Condensing the dynamics gives J=0.5*u'H*u+f'u+c. H is positive definite because the positive input penalty adds 2*0.2*I. A cyclic coordinate-descent solver exactly minimizes each coordinate over the box. It stops only when max |u - clip(u-(H*u+f))| <= 1e-8. This is a projected-gradient/KKT residual. Each update applies only u_0, shifts the sequence as a warm start, and solves again from the next observed state. Failed convergence raises an error; no unconverged sequence is silently accepted. Cap: 3,000 sweeps per QP. Weights and horizon are a transparent illustrative design, not optimized against the PID results. No parameter sweep was performed. Neither controller is asserted to be best tuned; change the settings before drawing conclusions for another task. The MPC is not MPPI, nonlinear MPC, robust MPC or a hardware controller. No closed-loop stability or safety guarantee follows from this finite-horizon example. RESULTS AND SAMPLE CONVENTIONS Each results.csv row contains start time, end time, common inputs, then the two states AFTER the held command has acted for 0.1 s. Each error is end-of-interval position minus that interval's reference, not a future setpoint. Metrics use all 180 endpoint errors, excluding the initial state. Integral absolute error uses a right-endpoint sum dt*sum(abs(error)). Command RMS uses the 180 actual held actuator commands. A saturated interval has |u| >= 1-1e-9; no total-acceleration limit is implied. Controller RMSE m IAE m*s command RMS m/s^2 saturated intervals PID 0.450121 4.190768 0.503059 27 / 180 MPC 0.439495 3.885315 0.517561 33 / 180 Final signed error: PID +0.018019 m; MPC -0.000061 m. All 180 QPs converged; maximum KKT residual 9.983433152220555e-9. Maximum solver sweeps: 248. Sweeps are not elapsed time or a deadline bound. Small floating-point/libm differences may alter trailing digits elsewhere. The response.svg plot is original and generated by the script. Its axes are sized for the published scenario; adapt the plotting limits for experiments outside the shown position range. Full numerical data remain in results.csv. Blue solid: MPC; red dashed: PID; grey dotted: reference. Shading indicates the unmeasured disturbance. The article also provides a numerical table. CHECKS AND LIMITS Nine executable checks cover exact plant evolution, condensed cost versus independent rollout, finite-difference gradients, an independent active-set oracle for a two-variable QP, anti-windup/no derivative kick, replay/causality/ constraints/independent metrics, equilibrium, invalid input timestamps, and replay input/output path collisions (including a symlink). The full published CSV replay was also checked for identical output bytes. These are software simulation results. No hardware run, measured computation time, power/energy measurement, sensor uncertainty, friction, backlash, coupling, payload variation, obstacle or joint limit is included. This scalar input-constrained example cannot establish performance on a robot. The MPC has no integral disturbance estimator and may retain offset under a persistent unknown disturbance; the published disturbance is temporary. PRIMARY REFERENCES (checked 3 December 2026; no external code bundled) Receding-horizon semantics and unmeasured disturbances: https://www.mathworks.com/help/mpc/gs/what-is-mpc.html Conditional integration / clamping: https://www.mathworks.com/help/simulink/slref/anti-windup-control-using-a-pid-controller.html Trajectory optimization, convex linear problems and MPC feasibility: https://underactuated.mit.edu/trajopt.html The scenario, solver, script, CSV data and SVG are original teaching artifacts. These references support the control concepts, not the numerical results here.