Chapter 6: Model Predictive Control (MPC)

What is MPC?

MPC solves an optimization problem at each time step:

  1. Predict future behavior using a model
  2. Optimize control inputs over a horizon
  3. Apply first control action
  4. Repeat

MPC Formulation

Minimize: J=āˆ‘k=0N(xkTQxk+ukTRuk)J = \sum_{k=0}^{N} (x_k^TQx_k + u_k^TRu_k)

Subject to:

  • System dynamics: xk+1=Axk+Bukx_{k+1} = Ax_k + Bu_k
  • Input constraints: umin≤uk≤umaxu_{min} \leq u_k \leq u_{max}
  • State constraints: xmin≤xk≤xmaxx_{min} \leq x_k \leq x_{max}

Simple MPC Implementation

import numpy as np
import cvxpy as cp

class MPC:
    def __init__(self, A, B, Q, R, N, u_min, u_max):
        self.A, self.B = A, B
        self.Q, self.R = Q, R
        self.N = N
        self.u_min, self.u_max = u_min, u_max
        self.n = A.shape[0]
        self.m = B.shape[1]
    
    def solve(self, x0, x_ref=None):
        if x_ref is None:
            x_ref = np.zeros(self.n)
        
        x = cp.Variable((self.n, self.N + 1))
        u = cp.Variable((self.m, self.N))
        
        cost = 0
        constraints = [x[:, 0] == x0]
        
        for k in range(self.N):
            cost += cp.quad_form(x[:, k] - x_ref, self.Q)
            cost += cp.quad_form(u[:, k], self.R)
            constraints += [
                x[:, k+1] == self.A @ x[:, k] + self.B @ u[:, k],
                u[:, k] >= self.u_min,
                u[:, k] <= self.u_max,
            ]
        
        prob = cp.Problem(cp.Minimize(cost), constraints)
        prob.solve()
        
        return u[:, 0].value

Key Parameters

Parameter Effect
N (horizon) Longer = better, but slower
Q (state weight) Higher = tighter tracking
R (input weight) Higher = smoother control

Next: Chapter 7 - Advanced MPC Techniques!