TExcelTAD
Home › Optimization › Quadratic Programming

Quadratic Programming

A quadratic program (QP) minimizes a quadratic objective subject to linear constraints:

min⁡ 12xTPx+qTxs.t.Gx≤h,Ax=b\min\ \frac{1}{2}\mathbf{x}^TP\mathbf{x} + \mathbf{q}^T\mathbf{x} \quad \text{s.t.} \quad G\mathbf{x} \le \mathbf{h}, \quad A\mathbf{x} = \mathbf{b}

With P⪰0P \succeq 0 it is convex and as tractable as an LP. QPs are everywhere: least squares with constraints, portfolio optimization, support vector machines, model predictive control of robots and vehicles, and the subproblems of SQP methods for general nonlinear optimization.

What changes from LPs

LP Convex QP
objective level sets parallel hyperplanes ellipsoids
optimum location at a vertex anywhere: interior, edge, face or vertex
algorithms simplex, interior point active set, interior point, ADMM (OSQP)
equality-only case trivial or unbounded one linear KKT solve

Because the optimum need not be a vertex, the simplex method does not apply directly; active-set methods generalize it.

Example: constrained least squares

Fit a monotone (non-decreasing) curve to noisy data: minimize ∥x−y∥2\lVert \mathbf{x} - \mathbf{y} \rVert^2 subject to x1≤x2≤⋯≤xnx_1 \le x_2 \le \dots \le x_n. This is isotonic regression, a QP with P=2IP = 2I and constraints xi−xi+1≤0x_i - x_{i+1} \le 0.

python · try it yourself
import numpy as np
from scipy.optimize import minimize

rng = np.random.default_rng(0)
n = 12
y = np.linspace(0, 3, n) + rng.normal(scale=0.6, size=n)
D = np.eye(n)[:-1] - np.eye(n)[1:]                        # rows: x_i - x_{i+1}
res = minimize(lambda x: np.sum((x - y)**2), y, jac=lambda x: 2 * (x - y),
               constraints=[{"type": "ineq", "fun": lambda x: -D @ x, "jac": lambda x: -D}],
               method="SLSQP", options={"ftol": 1e-12})
print("data:      ", np.round(y, 2))
print("isotonic:  ", np.round(res.x, 2))
# the pool-adjacent-violators algorithm gives the exact answer in O(n)
def pava(y):
    blocks = [[v, 1] for v in y]
    out = []
    for v, w in blocks:
        out.append([v, w])
        while len(out) > 1 and out[-2][0] > out[-1][0]:
            v2, w2 = out.pop(); v1, w1 = out.pop()
            out.append([(v1 * w1 + v2 * w2) / (w1 + w2), w1 + w2])
    return np.concatenate([[v] * w for v, w in out])
print("PAVA agrees:", np.allclose(res.x, pava(y), atol=1e-5))
data:       [0.08 0.19 0.93 0.88 0.77 1.58 2.42 2.48 1.76 1.7  2.35 3.02]
isotonic:   [0.08 0.19 0.86 0.86 0.86 1.58 2.09 2.09 2.09 2.09 2.35 3.02]
PAVA agrees: True

Where the data go down, neighbouring values are pooled into their average: those constraints are active.

Example: a small SVM as a QP

The hard-margin SVM finds the separating hyperplane with the widest margin: minimize 12∥w∥2\frac{1}{2}\lVert \mathbf{w} \rVert^2 s.t. yi(wTxi+b)≥1y_i(\mathbf{w}^T\mathbf{x}_i + b) \ge 1.

python · try it yourself
import numpy as np
from scipy.optimize import minimize

X = np.array([[1.0, 1.0], [2.0, 1.5], [1.5, 2.5], [4.0, 4.0], [5.0, 3.5], [4.5, 5.0]])
y = np.array([-1, -1, -1, 1, 1, 1])
cons = [{"type": "ineq", "fun": lambda v, i=i: y[i] * (v[:2] @ X[i] + v[2]) - 1} for i in range(6)]
res = minimize(lambda v: 0.5 * v[:2] @ v[:2], np.zeros(3), constraints=cons, method="SLSQP")
w, b = res.x[:2], res.x[2]
margins = y * (X @ w + b)
print("w =", np.round(w, 4), " b =", round(b, 4), " margin width =", round(2 / np.linalg.norm(w), 4))
print("support vectors (margin = 1):", np.where(np.isclose(margins, 1, atol=1e-6))[0])
w = [0.5882 0.3529]  b = -2.7647  margin width = 2.9155
support vectors (margin = 1): [2 3]

Only the support vectors have active constraints; removing any other point would not change the solution.

Non-convex QPs

If PP has a negative eigenvalue the QP is non-convex and, in general, NP-hard: local solvers return local minima, and global solvers use branch and bound. Always check P⪰0P \succeq 0 (for example np.linalg.eigvalsh(P).min() >= 0) before trusting a QP solver's answer as global.

In software

  • OSQP (ADMM-based, used in robotics MPC), qpOASES (active set), Clarabel, Gurobi, MOSEK; in Python, qpsolvers gives one interface to many of them. SciPy has no dedicated QP solver; SLSQP and trust-constr handle small ones.
  • scikit-learn's IsotonicRegression uses PAVA; libsvm solves the SVM dual QP with the SMO algorithm.

Exercises

Exercise 1: Convex or not?

Is the QP with P=[2332]P = \begin{bmatrix} 2 & 3 \\ 3 & 2 \end{bmatrix} convex?

Answer

No: the eigenvalues are 5 and −1-1.

Solution

det⁡P=4−9=−5<0\det P = 4 - 9 = -5 < 0, so the eigenvalues have opposite signs and PP is indefinite.

Exercise 2: Projection is a QP

Write "project z\mathbf{z} onto the polyhedron Gx≤hG\mathbf{x} \le \mathbf{h}" as a QP.

Answer

P=IP = I, q=−z\mathbf{q} = -\mathbf{z}, constraints Gx≤hG\mathbf{x} \le \mathbf{h}.

Solution

12∥x−z∥2=12xTx−zTx+const\frac{1}{2}\lVert \mathbf{x} - \mathbf{z} \rVert^2 = \frac{1}{2}\mathbf{x}^T\mathbf{x} - \mathbf{z}^T\mathbf{x} + \text{const}.

Exercise 3: PAVA by hand (code)

Apply PAVA to y=(1,3,2,4,3,5)\mathbf{y} = (1, 3, 2, 4, 3, 5).

Answer

(1,2.5,2.5,3.5,3.5,5)(1, 2.5, 2.5, 3.5, 3.5, 5).

Solution

The pairs (3,2)(3, 2) and (4,3)(4, 3) violate monotonicity and are each replaced by their mean.

python · try it yourself
import numpy as np
def pava(y):
    out = []
    for v in y:
        out.append([v, 1])
        while len(out) > 1 and out[-2][0] > out[-1][0]:
            v2, w2 = out.pop(); v1, w1 = out.pop()
            out.append([(v1 * w1 + v2 * w2) / (w1 + w2), w1 + w2])
    return [float(v) for v, w in out for _ in range(w)]
print(pava([1, 3, 2, 4, 3, 5]))
[1.0, 2.5, 2.5, 3.5, 3.5, 5.0]

Test yourself

A QP is convex when…

  1. P⪰0P \succeq 0
  2. all constraints are equalities
  3. q=0\mathbf{q} = 0
  4. PP is diagonal

Unlike an LP, the optimum of a convex QP…

  1. is always at a vertex
  2. can be in the interior or on any face
  3. never exists
  4. is always unique

In the SVM QP, the support vectors are the points whose constraints are…

  1. inactive
  2. active
  3. removed
  4. equalities