Convex optimization from scratch

Why convex problems are the ones we can actually solve, how to recognise them, and how they become a controller that drives a car.

Almost every engineering decision is an optimization problem: choose the inputs that make some cost as small as possible, without breaking any rules. Most such problems are hopeless to solve exactly. Convex problems are the great exception — whatever looks like the bottom is the bottom, and fast, reliable solvers will find it.

This course builds up the vocabulary of convexity — sets, cones, and the standard problem families — and then spends it on something real: model predictive control, where a car solves a fresh convex problem ten times a second to decide how hard to accelerate. The MPC lessons run that controller live in your browser.

Prerequisites

  • The linear algebra course, especially projection, least squares and quadratic forms.
  • Basic Python and NumPy.

Running the code

The scripts use CVXPY, a modelling layer that lets you write optimization problems the way you would on paper:

cd convex_optimization_from_scratch
pip install cvxpy==1.6.4 matplotlib scipy
python 0_big_picture.py

Each script is self-contained and plots its own figures. The MPC examples live under advanced/ and solve their problems with the OSQP solver that ships with CVXPY.

Lessons

  1. 1 The big pictureWhy one kind of landscape is easy to search and every other kind is a gamble.
  2. 2 Gradient descentWalking downhill one step at a time — and the one number that decides whether you arrive, oscillate or fly off.
  3. 3 Affine and convex setsMixing recipes in proportions that add up to 100% — and why forbidding negative amounts changes everything.
  4. 4 Convex conesDrop the "add up to one" rule and keep "never negative" — the shape behind colour mixing and most of optimization.
  5. 5 Least squares as a quadratic programThe same least-squares problem as in linear algebra — until you add realistic constraints and it becomes a QP.
  6. 6 Second-order conesThe ice-cream cone behind every "stay within this distance" constraint, from robot steps to safety margins.
  7. 7 Semidefinite programmingOptimising over matrices that must stay positive semidefinite — with a 2×2 case you can see completely.
  8. 8 DualityEvery minimisation problem casts a shadow — a maximisation that bounds it from below, and for convex problems meets it exactly.
  9. 9 Model predictive controlA controller that solves a fresh optimization problem every tenth of a second — running live, below, on the repo's car.
  10. 10 Stochastic MPCPlanning against sampled futures — and a precise answer to when the uncertainty actually changes the decision.
  11. 11 Beyond convexity: automatic differentiationGetting exact derivatives of any function you can write in code — the tool that lets gradient descent work on problems with no formula.

Browse this course's code on GitHub →