Dynamic Control Introduction
Learning outcomes
- Place planning, real-time optimization, MPC and regulatory control on their time scales and state what each passes to the next.
- Derive the LQR gain from the discrete algebraic Riccati equation for a linear model.
- Explain MPC as LQR with a finite horizon and constraints, and when the two give the same first move.
Book chapter: Nonlinear Dynamics, Oscillations, and Stabilization (Volume 7), Chapter 7, Inverted Pendulum Simulator for Balancing a Pole Without Losing the Cart (PDF).
Practice in 15 minutes: 11 · LQR Against MPC on a Finite Rail, 12 · LQR With a Kalman Filter, 13 · Input Shaping Against a Predictive Controller
Model: Linear state-space models (a vehicle here, a cart and pendulum in the exercises), physics-based or identified.
Decision: The controller chooses the inputs over the horizon; LQR does it in closed form, MPC by solving an optimization problem every cycle.
Learning: The model, and in adaptive schemes the gain, can come from data; the Riccati equation is also the value function that reinforcement learning approximates.
Dynamic control is a method to use model predictions to plan an optimized future trajectory for time-varying systems. It is often referred to as Model Predictive Control (MPC) or Dynamic Optimization.
A method to solve dynamic control problems is by numerically integrating the dynamic model at discrete time intervals, much like measuring a physical system at particular time points. The numerical solution is compared to a desired trajectory and the difference is minimized by adjustable parameters in the model that may change at every time step. The first control action is taken and then the entire process is repeated at the next time instance. The process is repeated because objective targets may change or updated measurements may have adjusted parameter or state estimates.
Where MPC Sits
| Layer | Typical period | Decides | Passes down |
|---|---|---|---|
| Planning and scheduling | days to weeks | what to make and when | production targets |
| Real-time optimization | hours | the most profitable steady state | setpoints and limits |
| Model predictive control | seconds to minutes | coordinated moves of several inputs | setpoints of the loops below |
| Regulatory control (PID) | below a second to seconds | one valve or heater each | actuator signals |
A safety system sits outside the hierarchy and acts on its own.
The Unconstrained Case: LQR
For a linear model `x_{k+1} = A x_k + B u_k` with weights `Q \succeq 0` on states and `R \succ 0` on inputs, the linear quadratic regulator minimizes an infinite-horizon cost:
$$\min_{u_0, u_1, \ldots} \; \sum_{k=0}^{\infty} \left( x_k^T Q\, x_k + u_k^T R\, u_k \right) \quad \text{s.t.} \quad x_{k+1} = A x_k + B u_k$$
The answer is a constant state feedback, `u_k = -K_{\text{LQR}}\, x_k`, with `P` the solution of the discrete algebraic Riccati equation:
$$\begin{gathered} P = Q + A^T P A - A^T P B \left(R + B^T P B\right)^{-1} B^T P A, \\ K_{\text{LQR}} = \left(R + B^T P B\right)^{-1} B^T P A \end{gathered}$$
The closed loop `A - B K_{\text{LQR}}` is stable when `(A, B)` is stabilizable and the states penalized by `Q` reveal every unstable mode. `x_k^T P x_k` is the optimal cost from state `x_k`.
MPC Is LQR With Constraints and a Finite Horizon
MPC solves the same problem over `N` steps, with input and state limits, and uses `P` as a terminal cost for what happens after the horizon:
$$\begin{gathered} \min_{u_0, \ldots, u_{N-1}} \; \sum_{k=0}^{N-1} \left( x_k^T Q\, x_k + u_k^T R\, u_k \right) + x_N^T P\, x_N \\ \text{s.t.}\quad x_{k+1} = A x_k + B u_k, \quad u_L \le u_k \le u_U, \quad x_L \le x_k \le x_U \end{gathered}$$
When no limit is active, its first move equals the LQR move. When a limit is active, LQR would ask for an input the actuator cannot give, while MPC plans around it. That difference, a pendulum that leaves the rail under LQR but not under MPC, is the subject of the first exercise listed at the top of this page.
Exercise
Objective: Implement a model predictive controller that automatically regulates vehicle velocity. Implement the controller in Excel, MATLAB, Python, or Simulink and tune the controller for acceptable performance. Discuss factors that may be important for evaluating controller performance. Estimated time: 1 hour
The dynamic relationship between a vehicle gas pedal position (MV) and velocity (CV) is given by the following set of conditions and a single dynamic equation.
Constants m = 500 ! Mass (kg) Parameters b = 50 ! Resistive coefficient (N-s/m) K = 0.8 ! Gain (m/s-%pedal) p = 0 >= 0 <= 100 ! Gas pedal position (%) Variables v = 0 ! initial condition Equations m * $v = -v * b + K * b * p
Implement a model predictive controller that adjusts gas pedal position to regulate velocity. Start at an initial vehicle velocity of 0 m/s and accelerate to a velocity of 40 m/s.
Discuss the controller performance and how it could be tuned to meet multiple objectives including:
- minimize travel time
- remain within speed limits
- improve vehicle fuel efficiency
- discourage excessive gas pedal adjustments
- do not accelerate excessively
There is no need to implement these advanced objectives in simulation for this second part of the exercise, only discuss the possible competing objectives.
Solution
Excel, MATLAB, Python, and Simulink are used in this example to both solve the differential equations that describe the velocity of a vehicle as well as minimize the control objective function.
from gekko import GEKKO
m = GEKKO()
m.time = np.linspace(0,20,41)
mass = 500
b = m.Param(value=50)
K = m.Param(value=0.8)
p = m.MV(value=0, lb=0, ub=100)
p.STATUS = 1 # allow optimizer to change
p.DCOST = 0.1 # smooth out gas pedal movement
p.DMAX = 20 # slow down change of gas pedal
v = m.CV(value=0)
v.STATUS = 1 # add the SP to the objective
m.options.CV_TYPE = 2 # sq error
v.SP = 40 # set point
v.TR_INIT = 1 # setpoint trajectory
v.TAU = 5 # time constant of setpoint trajectory
m.options.IMODE = 6 #control
m.Equation(mass*v.dt() == -v*b + K*b*p)
m.solve()
#%% Plot solution
import matplotlib.pyplot as plt
plt.figure()
plt.subplot(2,1,1)
plt.plot(m.time,p.value,'b-',lw=2)
plt.ylabel('gas')
plt.subplot(2,1,2)
plt.plot(m.time,v.value,'r--',lw=2)
plt.ylabel('velocity'); plt.xlabel('time')
plt.show()
- The first step to solve a model predictive control (MPC) in Python Gekko is to define the MPC problem. This may involve setting the time horizon and decision variables, constraints, objective function, and other parameters.
- Once the problem is defined, the next step is to create the MPC object. This is done by setting m.options.IMODE=6. The parameters of the MPC object can be set in m.options.
- The third step is to solve the MPC problem. This is done by calling the m.solve() command. This will solve the MPC problem and return the optimal solution.
- The fourth step is to process the solution. This can involve extracting the optimal decisions, evaluating the objective function, and other processing steps.
- Finally, the fifth step is to apply the optimal decisions. This can involve setting the plant state or inputs based on the optimal decisions.
Model Predictive Control is solved repeatedly at a specified cycle time as new measurements arrive or a new setpoint is specified. The model is updated with initial conditions from the next time step and the horizon is extended by an additional time unit to maintain a constant time horizon for predictive control.
from gekko import GEKKO
import matplotlib.pyplot as plt
from PIL import Image
# Initialize the GEKKO model
m = GEKKO(remote=False)
m.time = np.linspace(0, 20, 21) # Time grid
mass = 500
b = m.Param(value=50)
K = m.Param(value=0.8)
p = m.MV(value=0, lb=0, ub=100) # Manipulated Variable (gas pedal)
v = m.CV(value=0) # Controlled Variable (velocity)
# Define the dynamic equation
m.Equation(mass * v.dt() == -v * b + K * b * p)
# Set optimization mode for control
m.options.IMODE = 6 # Control mode
# Tuning parameters for MV (gas pedal)
p.STATUS = 1 # Allow optimizer to change
p.FSTATUS = 0
p.DCOST = 0.1 # Smooth out gas pedal movement
p.DMAX = 20 # Limit rate of change
# Tuning parameters for CV (velocity)
v.STATUS = 1 # Include set point in the objective
m.options.CV_TYPE = 2 # L2 norm
v.SP = 40 # Set point for velocity
v.TR_INIT = 1 # Enable set point trajectory
v.TAU = 5 # Time constant of trajectory
# List to store frames for GIF
frames = []
# Run the optimization in a loop and save plots
for i in range(25):
if i==15:
v.SP = 20
print(f'MPC cycle: {i} of 25')
m.solve(disp=False) # Solve the optimization problem
# Create a plot for each iteration
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 8))
ax1.plot(m.time+i, p.value, 'b-', lw=2)
ax1.set_ylabel('Gas Pedal (%)')
ax1.set_title(f'MPC Cycle {i+1}')
ax1.set_ylim([0,100])
ax2.plot(m.time+i, v.value, 'r--', lw=2)
ax2.plot(m.time+i,np.ones_like(m.time)*v.SP,'k:',lw=2)
ax2.set_ylim([0,50])
ax2.set_ylabel('Velocity (m/s)')
ax2.set_xlabel('Time (s)')
fig.tight_layout()
# Save the plot as an image frame
fig.canvas.draw()
frame = np.frombuffer(fig.canvas.tostring_rgb(), dtype='uint8')
frame = frame.reshape(fig.canvas.get_width_height()[::-1] + (3,))
frames.append(Image.fromarray(frame))
plt.close(fig) # Close the figure to save memory
# Save the frames as a GIF
frames[0].save('control_simulation.gif', format='GIF',
append_images=frames[1:], save_all=True, duration=500, loop=0)
print("GIF saved as 'control_simulation.gif'")

Generative AI Learning
Use these prompts after completing the cruise control exercise. Direct the AI - the controller design decisions are yours to defend.
Tip: Swap the story: the same model with a battery-power limit instead of a pedal is an electric-vehicle energy manager, where the competing objectives (trip time, energy per km, actuator wear, passenger comfort) are priced in real money. Ask the AI to help you restate your objective function with an explicit weight on energy and observe how the optimal velocity trajectory changes.
Check the answer: Check with scipy.linalg.solve_discrete_are: a = exp(-0.1) = 0.905, b = 0.8(1 - a) = 0.076, P ≈ 1.70 and gain ≈ 5.9 % pedal per m/s. Starting 40 m/s below the setpoint, that gain asks for about 236 % more pedal than the 50 % steady value, far beyond the 100 % limit. That is the case MPC handles and LQR does not.
What to Turn In
Submit a short report (PDF, 1-2 pages) that curates your results into a demonstration of what you learned. You may use Generative AI to help write the report, but you must guide it to the correct visualizations, justifications, and assumptions. Answer these questions:
- Include your velocity and pedal trajectories for the 0 to 40 m/s maneuver, with your horizon, discretization, and objective choices stated and justified.
- Show the effect of the move-suppression weight: the same maneuver with a small and a large delta-u penalty. What changed in the pedal, the velocity, and the objective value?
- How did you encode the competing objectives (time, speed limit, fuel/energy, pedal wear, acceleration comfort), and which pair actually conflicts in your solution? Show the evidence.
- From the debugging prompt: your committed diagnosis, the test you ran, and whether the evidence supported it.