Balancing & Optimal Control, step 5
MPC: respecting limits
With a 1 N motor, LQR crashes the cart into the stop. Plan the next 0.4 s within the limit, apply the first push and plan again: model predictive control makes the 20 cm move.
Builds on Optimisation: gradient descent, from the free Foundations.
Write and run this step in the simulator with ProLimits LQR doesn't know about
This motor gives at most 1 N, and the cart has to move 20 cm, from −10 cm to +10 cm, balancing all the way. LQR assumes it gets whatever force it asks for. Its first request is 4.6 N, backwards (to move the cart forwards it first tips the pole forwards); the motor clips that, the pole tips further than 1 N can ever bring back, and the cart chases it into the stop.
Model predictive control (MPC) plans within the limit instead. Every period it chooses the next forces that cost least over the next 0.4 s with every |u_k| \le u_\max, applies only, and plans again from the new state.
Predicting the horizon
Work with the error from the target, . The target is at rest, so . Step 1's rollout, written as matrices, stacks the next errors:
Block row is . Force reaches it through ; later forces can't reach back, so is zero above the diagonal.
The plan as a QP
The given cost_matrices weighs every predicted error with , the last one with LQR's , and every force with , and returns and . The cost of a plan becomes plus a constant, with .
Projected gradient
Step downhill, then clip back into the box:
U \leftarrow \mathrm{clip}\big(U - (HU + g)/L,\ -u_\max,\ u_\max\big), the largest eigenvalue of , gives the longest step that never overshoots. Start each solve from the last plan moved on one period (its last force repeated): it is nearly right already, so 100 steps are plenty.
Your task
predict_horizon(A, B, N): returnPhi, Gamma.projected_gradient(H, g, u_max, U0, iters): return .mpc(x): warm-start from the globalplan, store the new plan in it, return its first force.
The program runs LQR for 2 s, resets, then runs your MPC for 5 s. The white pole is where the plan expects to be 0.4 s ahead. MPC must reach +10 cm without asking for more than 1 N, leaning past 10° or touching a stop.