Module contents
Lesson 4 of 27Core 110 min

Convex problems: LP, QP, SOCP, SDP and disciplined convex programming

Recognize and reformulate convex problems in the LP, QP, SOCP and SDP standard-form hierarchy understood by solvers. Introduce disciplined convex programming with CVXPY and convex relaxations of hard problems, using MAXCUT and Goemans-Williamson rounding as the flagship example.

After this lesson you can

  • Transform problems into epigraph form, introduce slack variables and recognize equivalent reformulations.
  • Model real problems (robust regression, constrained least squares, portfolio allocation and filter design) as LPs, QPs, SOCPs or SDPs.
  • Write CVXPY problems that obey DCP rules and diagnose why an expression is rejected.
  • Construct the SDP relaxation of MAXCUT and extract an integer solution using random hyperplane rounding.
  • Explain what a conic solver does with the problem (canonicalization) and how to interpret its output status and residuals.

Before you start

Motivation: if it fits the form, it is solved

In the preceding two lessons you built the vocabulary: convex sets, cones and convex functions. This lesson uses it for what matters in practice: recognizing a convex problem, writing it in a form a program understands, and letting a solver solve it, with guarantees. The difference from the rest of the module is fundamental. For almost any other optimization problem you must choose an algorithm, tune steps and hope for the local optimum; for convex problems of the kinds in this lesson, polynomial-time algorithms and mature software exist, leaving the task of modeling well.

That phrase (modeling well) hides most of the craft. These real problems, suitably written, fall into the classes we will study:

  • Robust regression. Fitting a line to data with outliers by minimizing ∑i∣ri∣\sum_i \abs{r_i} instead of ∑iri2\sum_i r_i^2 gives a line barely moved by outliers. It is a linear program.
  • Portfolios. Choosing weights w\vb{w} that minimize risk w⊤Σw\vb{w}\T\mat{\Sigma}\vb{w} for a given expected return is a quadratic program; imposing a threshold on tail risk turns it into a second-order cone program.
  • Filter and experimental design. An FIR filter with the smallest maximum deviation from an ideal response is an ℓ∞\ell_\infty fit; an E-optimal experimental design maximizes the smallest eigenvalue of the information matrix, which depends affinely on the design weights.
  • Learning. Lasso, soft-margin SVM, nuclear-norm matrix completion and regularized logistic regression are convex problems with structure solvers exploit.
  • Hard problems. Even combinatorial problems are not excluded: a convex relaxation replaces the nonconvex part with a convex surrogate whose optimal value bounds the original problem’s value and whose solution can be rounded. You will see the flagship example: maximum cut of a graph, which is NP-hard, and a guaranteed approximation algorithm based on semidefinite programming.

The lesson climbs a ladder. First, what a convex problem is and why a local minimum is global. Then the transformations yielding equivalent problems and forming the grammar of modeling. Next, four rungs understood by solvers, in increasing expressive power: linear (LP), quadratic (QP), second-order cone (SOCP) and semidefinite programming (SDP). Then disciplined convex programming (DCP), the rules CVXPY uses to determine whether your formulation is convex and translate it to a cone. Finally, relaxations with MAXCUT. In the lab you will model two LPs by hand, implement the MAXCUT relaxation and rounding from scratch, and check everything using CVXPY.

What is a convex problem?

Recall the standard form of an optimization problem from lesson 1. With inequality constraints fi(x)≤0f_i(\vb{x}) \le 0 and equality constraints hj(x)=0h_j(\vb{x}) = 0, the problem is convex when all defining pieces are convex, with a special condition for equalities.

Three easily missed nuances:

  • A non-affine equality breaks convexity, even when the function is convex. Constraint ∥x∥2=1\norm{\vb{x}}_2 = 1 defines a sphere, which is not convex; ∥x∥2≤1\norm{\vb{x}}_2 \le 1 is the convex ball. An equality h(x)=0h(\vb{x}) = 0 is equivalent to the two inequalities h≤0h \le 0 and −h≤0-h \le 0, and only when hh is both convex and concave, that is affine, can both be convex.
  • Form matters, not just the set. The problem “minimize x1x_1 subject to ∥x∥2≥1\norm{\vb{x}}_2 \ge 1” is not convex because constraint 1−∥x∥2≤01 - \norm{\vb{x}}_2 \le 0 has a concave, not convex, function. But a nonconvex formulation can describe a convex set: {x:x1/(1+x22)≤0}\{x : x_1/(1 + x_2^2) \le 0\} is a half-plane, although its defining function is not convex. A problem’s convexity is a property of how it is written, and reformulation (below) means rewriting it so this becomes visible.
  • There are no longer “bad local optima”. This property makes the problems tractable.
Proof

Let x\vb{x} be a local minimum: it is feasible and there is an R>0R > 0 such that f0(x)≤f0(z)f_0(\vb{x}) \le f_0(\vb{z}) for all feasible z\vb{z} with ∥z−x∥2<R\norm{\vb{z} - \vb{x}}_2 < R. Suppose for a contradiction there is a feasible y\vb{y} with f0(y)<f0(x)f_0(\vb{y}) < f_0(\vb{x}). For θ∈(0,1)\theta \in (0, 1), z=(1−θ)x+θy\vb{z} = (1 - \theta)\vb{x} + \theta\vb{y} is feasible by convexity of the feasible set, and convexity of f0f_0 gives

f0(z)≤(1−θ)f0(x)+θf0(y)<f0(x).f_0(\vb{z}) \le (1 - \theta) f_0(\vb{x}) + \theta f_0(\vb{y}) < f_0(\vb{x}).

Since ∥z−x∥2=θ∥y−x∥2\norm{\vb{z} - \vb{x}}_2 = \theta\norm{\vb{y} - \vb{x}}_2, choose θ<R/∥y−x∥2\theta < R / \norm{\vb{y} - \vb{x}}_2 so z\vb{z} lies in the ball of radius RR and improves on x\vb{x}. This contradicts local minimality. The optimal set X⋆={x∈X:f0(x)≤p⋆}\mathcal{X}^\star = \{\vb{x} \in \mathcal{X} : f_0(\vb{x}) \le p^\star\} is a sublevel set of a convex function within a convex set, hence convex. And if f0f_0 were strictly convex and there were two distinct optima x1,x2\vb{x}_1, \vb{x}_2, their midpoint would be feasible with f0<p⋆f_0 < p^\star.

∎

The proof also explains what fails without convexity: in a nonconvex feasible set, the segment between a local minimum and a better point can leave the set, breaking the argument.

The optimality condition

For differentiable functions there is an exact characterization of the optimum, unifying all cases (constrained or unconstrained) in one geometric statement. Recall the first-order convexity condition, f(y)≥f(x)+∇f(x)⊤(y−x)f(\vb{y}) \ge f(\vb{x}) + \grad f(\vb{x})\T(\vb{y} - \vb{x}): the tangent lies below the function.

Proof

(⇐\Leftarrow) By the first-order condition, f0(y)≥f0(x⋆)+∇f0(x⋆)⊤(y−x⋆)≥f0(x⋆)f_0(\vb{y}) \ge f_0(\vb{x}^\star) + \grad f_0(\vb{x}^\star)\T(\vb{y} - \vb{x}^\star) \ge f_0(\vb{x}^\star) for every feasible y\vb{y}. (⇒\Rightarrow) Suppose x⋆\vb{x}^\star is optimal but there is y∈X\vb{y} \in \mathcal{X} with ∇f0(x⋆)⊤(y−x⋆)<0\grad f_0(\vb{x}^\star)\T(\vb{y} - \vb{x}^\star) < 0. The point z(θ)=x⋆+θ(y−x⋆)\vb{z}(\theta) = \vb{x}^\star + \theta(\vb{y} - \vb{x}^\star) is feasible for θ∈[0,1]\theta \in [0, 1] and  ⁣d ⁣dθf0(z(θ))∣θ=0=∇f0(x⋆)⊤(y−x⋆)<0\frac{\dd}{\dd\theta} f_0(\vb{z}(\theta))\big|_{\theta = 0} = \grad f_0(\vb{x}^\star)\T(\vb{y} - \vb{x}^\star) < 0, so f0(z(θ))<f0(x⋆)f_0(\vb{z}(\theta)) < f_0(\vb{x}^\star) for small θ>0\theta > 0. Contradiction.

∎

Remember the geometric reading: −∇f0(x⋆)-\grad f_0(\vb{x}^\star) is the steepest descent direction, and the condition says no feasible direction y−x⋆\vb{y} - \vb{x}^\star forms an acute angle with it. Thus hyperplane {y:∇f0(x⋆)⊤(y−x⋆)=0}\{\vb{y} : \grad f_0(\vb{x}^\star)\T(\vb{y} - \vb{x}^\star) = 0\} supports the feasible set at x⋆\vb{x}^\star (the supporting hyperplane theorem in action). Three direct consequences:

  • Unconstrained (X=Rn\mathcal{X} = \R^n). Taking y=x⋆−∇f0(x⋆)\vb{y} = \vb{x}^\star - \grad f_0(\vb{x}^\star) gives −∥∇f0(x⋆)∥2≥0-\norm{\grad f_0(\vb{x}^\star)}^2 \ge 0, so ∇f0(x⋆)=0\grad f_0(\vb{x}^\star) = \vb{0}. This is the first-order condition of lesson 1, now sufficient, not only necessary.
  • Equalities only (X={Ax=b}\mathcal{X} = \{\mat{A}\vb{x} = \vb{b}\}). Differences y−x⋆\vb{y} - \vb{x}^\star span the nullspace of A\mat{A}, which is a subspace, and a linear functional that is ≥0\ge 0 on a subspace vanishes there. Thus ∇f0(x⋆)⊥null⁡(A)\grad f_0(\vb{x}^\star) \perp \nullsp(\mat{A}), meaning ∇f0(x⋆)∈row⁡(A)\grad f_0(\vb{x}^\star) \in \row(\mat{A}): there is ν\vb{\nu} with ∇f0(x⋆)+A⊤ν=0\grad f_0(\vb{x}^\star) + \mat{A}\T\vb{\nu} = \vb{0}. This ν\vb{\nu} is a Lagrange multiplier, studied in lesson 5.
  • Nonnegative orthant (X={x≥0}\mathcal{X} = \{\vb{x} \ge \vb{0}\}). With y=x⋆+ei\vb{y} = \vb{x}^\star + \vb{e}_i we obtain ∂if0(x⋆)≥0\partial_i f_0(\vb{x}^\star) \ge 0, and with y=0\vb{y} = \vb{0}, ∇f0(x⋆)⊤x⋆≤0\grad f_0(\vb{x}^\star)\T\vb{x}^\star \le 0. Since x⋆≥0\vb{x}^\star \ge \vb{0}, the sum of nonnegative terms xi⋆ ∂if0(x⋆)x^\star_i\,\partial_i f_0(\vb{x}^\star) is both ≥0\ge 0 and ≤0\le 0: each term vanishes. This is complementary slackness in its simplest form: in each coordinate either the constraint is active (xi⋆=0x_i^\star = 0) or the gradient vanishes.

Reformulating without changing the answer

Almost nobody receives a problem already written in standard convex form. The job is to transform it until it is. Two problems are equivalent if one solution can be read from the other (with the same optimal value, or one derived from it), without further solving. You will use these transformations constantly.

TransformationBeforeAfterWhen convexity is preserved
Epigraph formmin⁡f0(x)\min f_0(\vb{x})min⁡t\min t subject to f0(x)≤tf_0(\vb{x}) \le talways, if f0f_0 is convex
Slack variablesg(x)≤0\vb{g}(\vb{x}) \le \vb{0}g(x)+s=0\vb{g}(\vb{x}) + \vb{s} = \vb{0}, s≥0\vb{s} \ge \vb{0}only if g\vb{g} is affine
Eliminate equalitiesAx=b\mat{A}\vb{x} = \vb{b}x=Fz+x0\vb{x} = \mat{F}\vb{z} + \vb{x}_0always (with F\mat{F} a basis of null⁡A\nullsp\mat{A})
Split signx\vb{x} freex=x+−x−\vb{x} = \vb{x}^+ - \vb{x}^-, x±≥0\vb{x}^\pm \ge \vb{0}always, in linear problems
Monotone objective functionmin⁡∥Ax−b∥2\min \norm{\mat{A}\vb{x} - \vb{b}}_2min⁡∥Ax−b∥22\min \norm{\mat{A}\vb{x} - \vb{b}}_2^2if the result remains convex

Epigraph form deserves special attention because it moves all the objective’s complexity into a constraint and leaves a linear objective. For a problem min⁡f0(x)\min f_0(\vb{x}) on X\mathcal{X}, epigraph form is

min⁡x,t  tsubject tof0(x)≤t,x∈X.\min_{\vb{x}, t} \; t \quad \text{subject to} \quad f_0(\vb{x}) \le t, \quad \vb{x} \in \mathcal{X}.
Proof

For fixed x∈X\vb{x} \in \mathcal{X}, values tt satisfying f0(x)≤tf_0(\vb{x}) \le t form a ray and the least is t=f0(x)t = f_0(\vb{x}). Minimizing first over tt and then over x\vb{x} (partial minimization does not change the joint optimum) gives min⁡x∈Xf0(x)\min_{\vb{x} \in \mathcal{X}} f_0(\vb{x}). If f0f_0 is convex, (x,t)↦f0(x)−t(\vb{x}, t) \mapsto f_0(\vb{x}) - t is convex, so the feasible set is convex.

∎

Every convex problem has a linear objective, without loss of generality: it is just a matter of where you put the nonlinear part. The first use is to turn a maximum into constraints.

Slacks work in reverse: they turn an affine inequality into an equality plus nonnegativity, the form preferred by LP algorithms. But watch the table’s third column.

Linear programming

The first and oldest class. It is the most restrictive and consequently the best understood.

Level sets {x:c⊤x=α}\{\vb{x} : \vb{c}\T\vb{x} = \alpha\} are parallel hyperplanes. Minimizing means moving a hyperplane in direction −c-\vb{c} to the last instant when it still touches the polyhedron. Since a polyhedron has flat faces, the last contact is almost always a corner, sometimes an entire face. The interactive explores all cases.

InteractiveThe geometry of an LP
12345
  • feasible region
  • −c-\vb{c} and level lines of c⊤x\vb{c}\T\vb{x}
  • optimum
Constraint 4
Simplex
Statusoptimal
Value p⋆p^\star−5.289
Solution(4.67, 2.67)
Active constraints2
Vertices5
Unique optimum at a vertex: at least two constraints intersect there.
Five half-planes (marks point toward the forbidden region) define the feasible region; the orange arrow is −c-\vb{c}, the descent direction. Rotate the cost with the lower-right dial and watch the optimum jump between vertices without passing through the interior. Choose “Cost parallel to a face”: what solutions are there now? Drag a line (filled handle) until the optimal vertex disappears. Switch to “Unbounded” and “Infeasible” and note which question each reading answers. Enable the walk: the simplex method descends along edges, from vertex to vertex, without looking inside.

What you just saw is a theorem. But it must be stated carefully, since not every polyhedron has vertices (a strip {0≤x1≤1}\{0 \le x_1 \le 1\} in R2\R^2 contains entire lines).

Proof

A polyhedron without lines is the sum of the convex hull of its vertices and the cone generated by its extreme rays (Minkowski-Weyl theorem, seen with polyhedra): X=conv⁡{v1,…,vk}+cone⁡{r1,…,rℓ}\mathcal{X} = \operatorname{conv}\{\vb{v}_1, \dots, \vb{v}_k\} + \operatorname{cone}\{\vb{r}_1, \dots, \vb{r}_\ell\}. If any ray satisfies c⊤rj<0\vb{c}\T\vb{r}_j < 0, then x+srj∈X\vb{x} + s\vb{r}_j \in \mathcal{X} for every s≥0s \ge 0 and the cost tends to −∞-\infty: unbounded. If all satisfy c⊤rj≥0\vb{c}\T\vb{r}_j \ge 0, every x∈X\vb{x} \in \mathcal{X} can be written x=∑iλivi+∑jμjrj\vb{x} = \sum_i \lambda_i \vb{v}_i + \sum_j \mu_j \vb{r}_j with λi,μj≥0\lambda_i, \mu_j \ge 0 and ∑iλi=1\sum_i \lambda_i = 1, and

c⊤x=∑iλi c⊤vi+∑jμj c⊤rj  ≥  min⁡ic⊤vi.\vb{c}\T\vb{x} = \sum_i \lambda_i\,\vb{c}\T\vb{v}_i + \sum_j \mu_j\,\vb{c}\T\vb{r}_j \;\ge\; \min_i \vb{c}\T\vb{v}_i.

The minimum of the kk vertex values is attainable and bounds the entire polyhedron from below: it is the optimum, attained at a vertex. The optimal set is X∩{c⊤x=p⋆}\mathcal{X} \cap \{\vb{c}\T\vb{x} = p^\star\}, and since {c⊤x≥p⋆}\{\vb{c}\T\vb{x} \ge p^\star\} contains X\mathcal{X}, that intersection is a face.

∎

The trichotomy (infeasible, unbounded or attained optimum) holds for every LP, including when the polyhedron contains lines: decompose X\mathcal{X} into a polyhedron without lines plus its lineality space, on which c\vb{c} must vanish for the problem to be bounded. What may be absent without the assumption is a vertex: in the strip above, minimizing x1x_1 has an entire line as its solution and no vertices.

Two practical consequences. First, an LP optimal solution can be sought among vertices, a finite set (though huge: with mm constraints in Rn\R^n there are up to (mn)\binom{m}{n} vertices). Dantzig’s simplex method (1947) exploits this: it jumps from one vertex to a neighboring one that improves cost until none does. Its worst case is exponential (Klee and Minty, 1972) and in practice it is very fast. Interior-point methods (Karmarkar, 1984), studied in lesson 16, cross the interior and have polynomial guarantees. Second, the solution need not be unique: if c\vb{c} is perpendicular to a face, the whole face is optimal and the solver returns only one point (a vertex with simplex, a point in the face’s relative interior if converging along an interior-point central path). Two solvers can return different answers, both correct. The optimal value is well defined.

The ℓ1\ell_1 and ℓ∞\ell_\infty norms are linear programs

A norm is not linear, but ∥r∥1\norm{\vb{r}}_1 and ∥r∥∞\norm{\vb{r}}_\infty are maxima and sums of absolute values of affine functions, and epigraph form turns them into LPs. For the fit min⁡x∥Ax−b∥1\min_{\vb{x}} \norm{\mat{A}\vb{x} - \vb{b}}_1 with A∈Rm×d\mat{A} \in \R^{m \times d}, introduce a variable tit_i for each residual ri=ai⊤x−bir_i = \vb{a}_i\T\vb{x} - b_i with ∣ri∣≤ti\abs{r_i} \le t_i, that is, −ti≤ri≤ti-t_i \le r_i \le t_i:

min⁡x,t  1⊤tsubject to−t≤Ax−b≤t.\min_{\vb{x}, \vb{t}} \; \vb{1}\T\vb{t} \quad \text{subject to} \quad -\vb{t} \le \mat{A}\vb{x} - \vb{b} \le \vb{t}.

This LP has d+md + m variables and 2m2m inequalities. Equivalence follows from the epigraph theorem applied term by term: for fixed x\vb{x}, the least feasible 1⊤t\vb{1}\T\vb{t} is attained at ti=∣ri∣t_i = \abs{r_i}. For ∥Ax−b∥∞\norm{\mat{A}\vb{x} - \vb{b}}_\infty, one variable tt suffices to bound all residuals, −t1≤Ax−b≤t1-t\vb{1} \le \mat{A}\vb{x} - \vb{b} \le t\vb{1}, and minimize it: this is the guided proof exercise at the end. Both are LPs, so have vertex solutions, saying something concrete about the line they fit.

Proof

Each LP’s feasible polyhedron contains no lines because A\mat{A} has full column rank: a line in direction (q,τ)(\vb{q}, \tau) would require (q,τ)(\vb{q}, \tau) and (−q,−τ)(-\vb{q}, -\tau) to satisfy the homogeneous constraints ∣(Aq)i∣≤τi\abs{(\mat{A}\vb{q})_i} \le \tau_i, forcing τ=0\tau = 0 and Aq=0\mat{A}\vb{q} = \vb{0}, that is q=0\vb{q} = \vb{0}. By the fundamental theorem there is a vertex optimum. In Rd+m\R^{d+m} a vertex has d+md + m linearly independent active constraints. For ℓ1\ell_1, each index ii contributes at most two active constraints, and only if ri=0r_i = 0 (if ri≠0r_i \ne 0 only one of ti=rit_i = r_i, ti=−rit_i = -r_i can be active). With zz zero residuals there are at most (m−z)+2z=m+z(m - z) + 2z = m + z active constraints, and m+z≥m+dm + z \ge m + d forces z≥dz \ge d. For ℓ∞\ell_\infty, in Rd+1\R^{d+1} a vertex has d+1d + 1 active constraints, each of the form ±ri=t\pm r_i = t, and with t⋆>0t^\star > 0 one index cannot have both, so there are d+1d + 1 distinct indices.

∎

Thus the ℓ1\ell_1 line passes exactly through (at least) two data points, and the other residuals can have any magnitude without affecting the line except through their signs. This explains its robustness: the optimality condition (in terms of subgradients, seen in lesson 10) is ∑isi ai=0\sum_i s_i\,\vb{a}_i = \vb{0} for certain si=sign⁡(ri)s_i = \operatorname{sign}(r_i) if ri≠0r_i \ne 0 and si∈[−1,1]s_i \in [-1, 1] if ri=0r_i = 0, so a nonzero residual contributes only its sign and a large one pushes as much as a small one. By contrast ℓ2\ell_2 weights each residual by size. And ℓ∞\ell_\infty is the opposite: a line watching only the worst datum, with a band supported by d+1d + 1 points.

InteractiveThree norms, three lines
  • ℓ2: minimizes ∑ri2\sum r_i^2
  • ℓ1: minimizes ∑∣ri∣\sum\abs{r_i}
  • ℓ∞: minimizes max⁡∣ri∣\max\abs{r_i} (dashed band)
  • data point
Both LP fits land on vertices: the ℓ1\ell_1 line passes exactly through two data points and the ℓ∞\ell_\infty band is supported by three.
Data
Lines
ℓ2: slope, intercept0.28, 2.16
ℓ1: slope, intercept0.63, 1.12
ℓ∞: slope, intercept−0.01, 4.00
Maximum ℓ1 residual5.49
Points on the ℓ1 line2
Points on the ℓ∞ band3
The points are draggable data; the red point is an outlier that can be enabled or disabled. With all three lines on, disable and re-enable the outlier: the least-squares (ℓ2\ell_2) line turns toward it, ℓ1\ell_1 barely moves, and ℓ∞\ell_\infty is taken over. Rings mark the data defining each LP vertex: two for ℓ1\ell_1 and three for ℓ∞\ell_\infty. Drag a ringed point on the ℓ1\ell_1 line far from its position and watch the line follow it; drag an unringed point without crossing the line and check that the ℓ1\ell_1 line does not move at all: only the sign of its residual matters, not its size.

Quadratic programming

An LP cannot have its optimum inside the region or penalize distance. Replacing the linear objective with a quadratic gives the next rung.

The condition P⪰0\mat{P} \succeq \mat{0} is not decorative. With just one direction of negative curvature the problem is already NP-hard in general (Pardalos and Vavasis, 1991). A convex QP solver therefore requires (or checks) that P\mat{P} be semidefinite. Common applications:

  • Constrained least squares. ∥Ax−b∥22=x⊤(A⊤A)x−2(A⊤b)⊤x+∥b∥2\norm{\mat{A}\vb{x} - \vb{b}}_2^2 = \vb{x}\T(\mat{A}\T\mat{A})\vb{x} - 2(\mat{A}\T\vb{b})\T\vb{x} + \norm{\vb{b}}^2 is quadratic with P=2A⊤A⪰0\mat{P} = 2\mat{A}\T\mat{A} \succeq \mat{0}, so adding bounds l≤x≤u\vb{l} \le \vb{x} \le \vb{u} or x≥0\vb{x} \ge \vb{0} leaves a QP. So does lasso, ∥Ax−b∥22+λ∥x∥1\norm{\mat{A}\vb{x} - \vb{b}}_2^2 + \lambda\norm{\vb{x}}_1, after sign splitting and adding the variables from the preceding LP.
  • Projection onto a polyhedron. min⁡∥x−p∥22\min \norm{\vb{x} - \vb{p}}_2^2 subject to Gx≤h\mat{G}\vb{x} \le \vb{h} is the Euclidean projection of p\vb{p} onto the polyhedron.
  • Markowitz portfolios. With weights w\vb{w}, expected returns μ\vb{\mu} and covariance Σ⪰0\mat{\Sigma} \succeq \mat{0}: min⁡12w⊤Σw−γ μ⊤w\min \tfrac{1}{2}\vb{w}\T\mat{\Sigma}\vb{w} - \gamma\,\vb{\mu}\T\vb{w} subject to 1⊤w=1\vb{1}\T\vb{w} = 1, w≥0\vb{w} \ge \vb{0}. Parameter γ≥0\gamma \ge 0 trades risk against return.
  • Soft-margin SVM, with slack variables and a quadratic in the weights.

With equalities only there is a very useful special case. The optimality condition ∇f0+A⊤ν=0\grad f_0 + \mat{A}\T\vb{\nu} = \vb{0} derived above becomes linear, because ∇f0(x)=Px+q\grad f_0(\vb{x}) = \mat{P}\vb{x} + \vb{q}. The problem reduces to solving a linear system, the KKT system:

[PA⊤A0][xν]=[−qb].\begin{bmatrix} \mat{P} & \mat{A}\T \\ \mat{A} & \mat{0} \end{bmatrix}\begin{bmatrix} \vb{x} \\ \vb{\nu} \end{bmatrix} = \begin{bmatrix} -\vb{q} \\ \vb{b} \end{bmatrix}.

Each step of interior-point and active-set methods solves systems of this form. This illustrates how the lowest rung supports the others.

Second-order cone programming

Some problems with norms (not squared) are not QPs: min⁡∥Ax−b∥2\min \norm{\mat{A}\vb{x} - \vb{b}}_2 with ∥x∥2≤1\norm{\vb{x}}_2 \le 1 is convex but has a quadratic constraint. The tool is the second-order cone of the previous lesson:

Qn+1={(y,s)∈Rn×R:∥y∥2≤s}.\mathcal{Q}^{n+1} = \{(\vb{y}, s) \in \R^n \times \R : \norm{\vb{y}}_2 \le s\}.

SOCPs contain convex QPs, and the proof is an algebraic identity worth memorizing.

Proof

(⇐\Leftarrow) The inequality on the right requires t+1≥0t + 1 \ge 0, and squaring gives 4∥Lx∥2+(t−1)2≤(t+1)24\norm{\mat{L}\vb{x}}^2 + (t - 1)^2 \le (t + 1)^2. Since (t+1)2−(t−1)2=4t(t + 1)^2 - (t - 1)^2 = 4t, this is equivalent to 4∥Lx∥2≤4t4\norm{\mat{L}\vb{x}}^2 \le 4t. (⇒\Rightarrow) If ∥Lx∥2≤t\norm{\mat{L}\vb{x}}^2 \le t, then t≥0t \ge 0, so t+1>0t + 1 > 0, squaring is an equivalence, and the same calculation runs backward.

∎

The usefulness of second-order cones appears in robust optimization. Imagine an LP min⁡c⊤x\min \vb{c}\T\vb{x} subject to a⊤x≤β\vb{a}\T\vb{x} \le \beta where vector a\vb{a} is not exactly known, only that it lies in the ellipsoid E={aˉ+Pu:∥u∥2≤1}\mathcal{E} = \{\bar{\vb{a}} + \mat{P}\vb{u} : \norm{\vb{u}}_2 \le 1\}. Requiring the constraint for every a∈E\vb{a} \in \mathcal{E} seems to require infinitely many constraints. But

sup⁡a∈Ea⊤x=aˉ⊤x+sup⁡∥u∥2≤1u⊤(P⊤x)=aˉ⊤x+∥P⊤x∥2,\sup_{\vb{a} \in \mathcal{E}} \vb{a}\T\vb{x} = \bar{\vb{a}}\T\vb{x} + \sup_{\norm{\vb{u}}_2 \le 1} \vb{u}\T(\mat{P}\T\vb{x}) = \bar{\vb{a}}\T\vb{x} + \norm{\mat{P}\T\vb{x}}_2,

by Cauchy-Schwarz (the supremum is attained with u\vb{u} aligned with P⊤x\mat{P}\T\vb{x}). The robust constraint is therefore one SOCP constraint, aˉ⊤x+∥P⊤x∥2≤β\bar{\vb{a}}\T\vb{x} + \norm{\mat{P}\T\vb{x}}_2 \le \beta: the margin subtracted from β\beta is proportional to the norm of x\vb{x} measured by the uncertainty. This is the same pattern as the portfolio risk constraint ∥Σ1/2w∥2≤σmax⁡\norm{\mat{\Sigma}^{1/2}\vb{w}}_2 \le \sigma_{\max}, which bounds the standard deviation of return and naturally limits risk with an SOCP.

The same argument yields robust least squares. If the data matrix is A+Δ\mat{A} + \mat{\Delta} with unknown perturbation of spectral norm ∥Δ∥2≤ρ\norm{\mat{\Delta}}_2 \le \rho, the worst-case residual is

sup⁡∥Δ∥2≤ρ∥(A+Δ)x−b∥2=∥Ax−b∥2+ρ∥x∥2.\sup_{\norm{\mat{\Delta}}_2 \le \rho} \norm{(\mat{A} + \mat{\Delta})\vb{x} - \vb{b}}_2 = \norm{\mat{A}\vb{x} - \vb{b}}_2 + \rho\norm{\vb{x}}_2 .

The ≤\le inequality is the triangle inequality with ∥Δx∥2≤ρ∥x∥2\norm{\mat{\Delta}\vb{x}}_2 \le \rho\norm{\vb{x}}_2, and equality is attained with Δ=ρ ux⊤/∥x∥2\mat{\Delta} = \rho\,\vb{u}\vb{x}\T/\norm{\vb{x}}_2, where u\vb{u} is the normalized residual Ax−b\mat{A}\vb{x} - \vb{b} (if x=0\vb{x} = \vb{0} or the residual is zero, any choice works). Minimizing a sum of two Euclidean norms is an SOCP with two cones, and its close relative, minimizing ∥Ax−b∥2\norm{\mat{A}\vb{x} - \vb{b}}_2 subject to ∥x∥2≤r\norm{\vb{x}}_2 \le r, is what you will solve with CVXPY in the lab.

SOCPs therefore cover norm-constrained least squares (such as ridge regression in constrained form), problems with ellipsoidal uncertainty, facility location with Euclidean distances, and many more. They use the same machinery as LPs, somewhat more expensive per iteration.

Semidefinite programming

The last rung replaces the orthant or second-order cone with the positive semidefinite cone S+k\mathbb{S}^k_+, the cone of symmetric k×kk \times k matrices with nonnegative eigenvalues.

An LMI is in fact infinitely many linear inequalities at once (v⊤F(x)v≥0\vb{v}\T F(\vb{x})\vb{v} \ge 0 for every v\vb{v}), explaining its expressive power. Three identities yield almost all applications.

The maximum eigenvalue. Since eigenvalues of tI−Mt\mat{I} - \mat{M} are t−λi(M)t - \lambda_i(\mat{M}), λmax⁡(M)≤t  ⟺  tI−M⪰0\lambda_{\max}(\mat{M}) \le t \iff t\mat{I} - \mat{M} \succeq \mat{0}. Thus, for a matrix depending affinely on x\vb{x}, M(x)=A0+∑ixiAi\mat{M}(\vb{x}) = \mat{A}_0 + \sum_i x_i\mat{A}_i,

min⁡xλmax⁡(M(x))⟺min⁡x,t  tsubject totI−M(x)⪰0.\min_{\vb{x}} \lambda_{\max}\big(\mat{M}(\vb{x})\big) \quad \Longleftrightarrow \quad \min_{\vb{x}, t} \; t \quad \text{subject to} \quad t\mat{I} - \mat{M}(\vb{x}) \succeq \mat{0}.

This is an SDP, appearing in control (stability via Lyapunov functions), experimental design, and bounds on a matrix’s spectral norm.

The Schur complement. If C≻0\mat{C} \succ \mat{0}, then [ABB⊤C]⪰0  ⟺  A−BC−1B⊤⪰0\begin{bmatrix} \mat{A} & \mat{B} \\ \mat{B}\T & \mat{C} \end{bmatrix} \succeq \mat{0} \iff \mat{A} - \mat{B}\mat{C}\inv\mat{B}\T \succeq \mat{0} (the Schur complement). With A=tI\mat{A} = t\mat{I}, column B=x\mat{B} = \vb{x} and C=t\mat{C} = t, for t>0t > 0,

∥x∥2≤t  ⟺  [tIxx⊤t]⪰0,\norm{\vb{x}}_2 \le t \iff \begin{bmatrix} t\mat{I} & \vb{x} \\ \vb{x}\T & t \end{bmatrix} \succeq \mat{0},

because the complement is tI−xx⊤/t⪰0t\mat{I} - \vb{x}\vb{x}\T/t \succeq \mat{0}, whose smallest eigenvalue is t−∥x∥2/t≥0t - \norm{\vb{x}}^2/t \ge 0. The equivalence also holds for t≤0t \le 0: with t=0t = 0 both sides force x=0\vb{x} = \vb{0} (a semidefinite matrix with zero diagonal is zero), and with t<0t < 0 neither holds (the matrix diagonal would be negative). Thus every SOCP is an SDP (each second-order cone constraint becomes an LMI), and hence LP ⊂\subset QP ⊂\subset SOCP ⊂\subset SDP. Why not always solve as SDP? Cost: an LMI of order kk adds k(k+1)/2k(k+1)/2 variables and each interior-point iteration is much more expensive than with a second-order cone. Stay on the lowest possible rung.

The nuclear norm. The sum of singular values ∥X∥∗=∑iσi(X)\norm{\mat{X}}_* = \sum_i \sigma_i(\mat{X}) is the best convex surrogate for rank (its convex envelope on the spectral norm unit ball, Fazel, 2002) and can be written as an SDP: ∥X∥∗≤t\norm{\mat{X}}_* \le t if and only if there are W1,W2\mat{W}_1, \mat{W}_2 with [W1XX⊤W2]⪰0\begin{bmatrix} \mat{W}_1 & \mat{X} \\ \mat{X}\T & \mat{W}_2 \end{bmatrix} \succeq \mat{0} and tr⁡W1+tr⁡W2≤2t\tr\mat{W}_1 + \tr\mat{W}_2 \le 2t (Recht, Fazel and Parrilo, 2010). With it, matrix completion (filling unknown entries of an assumed low-rank matrix) is the SDP “minimize ∥Z∥∗\norm{\mat{Z}}_* subject to Zij=MijZ_{ij} = M_{ij} on observed entries”, which you will see in the lab.

You now have the four rungs. The next interactive shows how each term in a real problem raises its minimum class, and what a solver does with it.

InteractiveThe LP, QP, SOCP, SDP ladder
SDPSOCPQP‖·‖₂²LPλ‖x‖1
Exponential coneoutside the linear, quadratic and semidefinite ladder: accepted by Clarabel and SCS.
  • minimum class
  • classes also containing it
  • active term
K=R+40\mathcal{K} = \R_+^{40}
Standard-form cone after canonicalization
HiGHSacceptsOSQPacceptsClarabelacceptsSCSaccepts
Each ∣xi∣\abs{x_i} in ℓ1\ell_1 adds a variable tit_i with −ti≤xi≤ti-t_i \le x_i \le t_i: new variables and linear constraints, but no higher class. The quadratic part fixes it at QP.
Objective terms (summed)
Constraints
Sizes
100
20
10
Minimum classQP
Auxiliary variables20
Linear inequalities40
Second-order conesnone
Semidefinite conesnone
Exponential cones0
Choose a problem from the gallery or toggle objective and constraint terms. The ladder marks the lowest rung, the maximum of the ranks of present terms. Below it, canonicalization additions (auxiliary variables, linear inequalities and cones) are counted for sizes mm, nn and kk set with sliders, along with solvers accepting the problem. Try lasso: what rung is it on? Add ∥x∥2≤1\norm{\vb{x}}_2 \le 1 and see it rise. Select “A trap: norm above” and see why it fits no rung.

One observation about the ladder: it is not a list of four different things but an expansion of the cone K\mathcal{K} in which the problem lives. After introducing auxiliary variables, every problem in this lesson can be written as

min⁡z  c⊤zsubject toAz+s=b,s∈K,\min_{\vb{z}} \; \vb{c}\T\vb{z} \quad \text{subject to} \quad \mat{A}\vb{z} + \vb{s} = \vb{b}, \quad \vb{s} \in \mathcal{K},

where K\mathcal{K} is a product of orthants R+p\R_+^p (LP), second-order cones Qd\mathcal{Q}^d (SOCP) and semidefinite cones S+k\mathbb{S}_+^k (SDP), and, if needed, the exponential cone (for log⁡\log and exp⁡\exp). This is the conic form received by solvers, and what we call canonicalization below.

Disciplined convex programming

Recognizing a convex problem is generally difficult to automate: deciding whether a degree-4 polynomial is convex is already NP-hard (Ahmadi, Olshevsky, Parrilo and Tsitsiklis, 2013), let alone an arbitrary function. Grant, Boyd and Ye’s (2006) answer was to restrict the language: a set of atoms with known curvature and composition rules guaranteeing convexity. If the formulation satisfies them, convexity is certified; otherwise the system does not say the problem is nonconvex, but that it cannot prove it. This is disciplined convex programming (DCP), implemented in CVXPY (Diamond and Boyd, 2016).

Each expression has curvature (constant, affine, convex, concave, or none) and a sign (positive, negative, unknown). Atoms (sum_squares, norm, exp, log, sqrt, max, quad_over_lin…) have tabulated curvature and monotonicity per argument, which can depend on its sign (square is increasing only for nonnegative arguments). Composition is the rule connecting everything.

This is the syntactic version of convexity calculus. The proof idea is visible in one case: if hh is convex and nondecreasing and gg is convex, then h(g(θx+(1−θ)y))≤h(θg(x)+(1−θ)g(y))≤θh(g(x))+(1−θ)h(g(y))h(g(\theta\vb{x} + (1 - \theta)\vb{y})) \le h(\theta g(\vb{x}) + (1 - \theta)g(\vb{y})) \le \theta h(g(\vb{x})) + (1 - \theta)h(g(\vb{y})): the first inequality uses convexity of gg and the fact hh is nondecreasing; the second uses convexity of hh. The remaining cases are analogous.

A DCP problem minimizes a convex expression (or maximizes a concave one) subject to “convex ≤\le concave” and “affine == affine” constraints. Everything else is rejected. Since DCP is only sufficient, it rejects some convex functions. The interactive lets you try expressions and see, node by node, where the rule fails.

InteractiveDoes DCP accept it?
sqrt(1 + x^2)no DCP curvaturesign ?
sqrt is concave and increasing
Rule not satisfied: sqrt is concave and increasing in this argument, so it must be concave; but 1 + x^2 is convex.
1 + x^2convex≥ 0
sum: constant + convex
1constant≥ 0
x^2convex≥ 0
a^2 even p is convex; increasing if a ≥ 0 and decreasing if a ≤ 0
xaffinesign ?
variable of unknown sign
  • constant
  • affine
  • convex
  • concave
  • no DCP curvature
DCP rejects it, but sampling finds it convex across 1500 point pairs: DCP provides sufficient rules, not a convexity test.
How to fix it. Write the root as a norm: sqrt(1 + x²) = ‖(1, x)‖₂, or norm([1, x]). The norm atom is convex with affine arguments.
Nonnegative variables
DCP verdictrejected
Inferred signsign ?
Numerical samplingconvex
Tree nodes5
Enter an expression in xx, yy and zz, or select one from the list. In the tree, each node shows its curvature and sign under DCP rules; the offending node is marked with the reason. Beside the verdict, numerical sampling says whether the function is actually convex, showing the difference between “not convex” and “convex but uncertified”. Start with 1+x2\sqrt{1 + x^2}: it is convex but DCP rejects it. Rewrite it as norm([1, x]) and see it accepted. Try x * y, log(exp(x)) and sqrt(x * y) versus geo_mean(x, y).

The central example: 1+x2\sqrt{1 + x^2} is the Euclidean norm of vector (1,x)(1, x) and therefore convex, but written as sqrt(1 + x^2) it composes ⋅\sqrt{\cdot} (concave and increasing) with 1+x21 + x^2 (convex), satisfying none of the three conditions. Written as norm(hstack([1, x])) it is an atom with an affine argument, and DCP accepts it. More rules of thumb you will see repeatedly: x * y is accepted only if one factor is constant (a product of variables is neither convex nor concave); log(exp(x)) is rejected even though it is the affine function xx (concave of convex); x**2 / y is written quad_over_lin(x, y); and the concave geometric mean xy\sqrt{xy} is written geo_mean. The atom list has its own logic, documented in the manual; understanding the mechanism is what matters.

From expression to cone

DCP does more than decide. Every atom has a graph implementation: a description of its epigraph (if convex) or hypograph (if concave) using cones. For example, ∥y∥2≤t\norm{\vb{y}}_2 \le t is a second-order constraint and λmax⁡(M)≤t\lambda_{\max}(\mat{M}) \le t is an LMI. CVXPY traverses the tree replacing each atom with an auxiliary variable plus the corresponding conic constraints, ending with the conic problem (c,A,b,K)(\vb{c}, \mat{A}, \vb{b}, \mathcal{K}) above. For example, min⁡∥Ax−b∥2+λ∥x∥1\min \norm{\mat{A}\vb{x} - \vb{b}}_2 + \lambda\norm{\vb{x}}_1 becomes

min⁡x,t,u  t+λ 1⊤usubject to∥Ax−b∥2≤t,−u≤x≤u,\min_{\vb{x}, t, \vb{u}} \; t + \lambda\,\vb{1}\T\vb{u} \quad \text{subject to} \quad \norm{\mat{A}\vb{x} - \vb{b}}_2 \le t, \quad -\vb{u} \le \vb{x} \le \vb{u},

with a second-order cone of dimension m+1m + 1 and 2n2n linear inequalities. It then gives this problem to a conic solver and translates the solution back. Common solvers differ in what they accept and how they work: HiGHS (LP and MIP, simplex and interior point), OSQP (QP, with ADMM), Clarabel (interior point for LP, QP, SOCP, SDP and exponential and power cones, the general-purpose solver in recent CVXPY versions), and SCS (first order with ADMM, for cones of all kinds at large scale and low precision). Interior-point methods give high precision but each iteration factorizes a matrix; first-order methods scale better with modest precision.

Convex relaxations: MAXCUT

Nonconvex problems are tackled by replacing them with convex problems that bound the original. A relaxation does not solve the hard problem, but gives two valuable things: a bound on its optimal value and a relaxed solution often roundable to a feasible solution of the original.

The inequality is immediate: every feasible point of the original is feasible in the relaxation at no greater cost. Examples: replace xi∈{0,1}x_i \in \{0, 1\} with xi∈[0,1]x_i \in [0, 1] (linear relaxation of an integer problem), replace rank with nuclear norm, or use the semidefinite relaxation below. If the relaxed solution happens to be feasible for the original problem, it is optimal for it as well, and the relaxation is called exact; generally there is an integrality gap.

MAXCUT and its semidefinite relaxation

Given graph G=(V,E)G = (V, E) with weights wij≥0w_{ij} \ge 0 (a graph without loops, n=∣V∣n = \abs{V}), a cut partitions vertices into two sets and its value is the sum of weights of crossing edges. MAXCUT asks for the maximum-value cut. It is NP-hard (appearing in Karp’s 1972 list of 21 problems), so we do not expect an efficient exact algorithm, unlike the minimum cut between two vertices, a maximum flow problem solvable in polynomial time (max-flow min-cut theorem).

Encode a partition with xi=±1x_i = \pm 1: edge (i,j)(i, j) crosses if and only if xixj=−1x_i x_j = -1, and 1−xixj2\tfrac{1 - x_ix_j}{2} is 1 if it crosses, 0 otherwise. Then

MAXCUT=max⁡x∈{±1}n  ∑i<jwij 1−xixj2.\text{MAXCUT} = \max_{\vb{x} \in \{\pm 1\}^n} \; \sum_{i < j} w_{ij}\,\frac{1 - x_ix_j}{2}.

Relax each xi∈{±1}x_i \in \{\pm 1\} to a unit vector vi∈Rn\vb{v}_i \in \R^n, ∥vi∥2=1\norm{\vb{v}_i}_2 = 1, and replace the product with the inner product:

SDP=max⁡∥v1∥2=⋯=∥vn∥2=1  ∑i<jwij 1−vi⊤vj2.\text{SDP} = \max_{\norm{\vb{v}_1}_2 = \cdots = \norm{\vb{v}_n}_2 = 1} \; \sum_{i < j} w_{ij}\,\frac{1 - \vb{v}_i\T\vb{v}_j}{2}.

Since xi∈{±1}x_i \in \{\pm 1\} are a special case (vi=xie1\vb{v}_i = x_i\vb{e}_1), this is a relaxation: SDP≥MAXCUT\text{SDP} \ge \text{MAXCUT} (for maximization the bound is upper). Why is it called “semidefinite”? With Xij=vi⊤vjX_{ij} = \vb{v}_i\T\vb{v}_j, Gram matrix X=V⊤V\mat{X} = \mat{V}\T\mat{V} (with V=[v1⋯vn]\mat{V} = [\vb{v}_1 \cdots \vb{v}_n] as columns) satisfies X⪰0\mat{X} \succeq \mat{0}, Xii=1X_{ii} = 1, and the objective is linear in X\mat{X}:

max⁡X∈Sn  14tr⁡(LX)subject toXii=1,  X⪰0,\max_{\mat{X} \in \mathbb{S}^n} \; \tfrac{1}{4}\tr(\mat{L}\mat{X}) \quad \text{subject to} \quad X_{ii} = 1, \; \mat{X} \succeq \mat{0},

where L=diag⁡(W1)−W\mat{L} = \diag(\mat{W}\vb{1}) - \mat{W} is the Laplacian. The original problem is exactly the same with the extra constraint rank⁡X=1\rank\mat{X} = 1 (since X=xx⊤\mat{X} = \vb{x}\vb{x}\T). Removing the rank constraint, the nonconvex part, yields the relaxation: {X⪰0,Xii=1}\{\mat{X} \succeq \mat{0}, X_{ii} = 1\} (the elliptope, the set of correlation matrices) is convex and contains every xx⊤\vb{x}\vb{x}\T. A result by Barvinok and Pataki guarantees an optimum of rank rr with r(r+1)/2≤nr(r+1)/2 \le n, that is, r≤2nr \le \sqrt{2n}, so vectors vi\vb{v}_i can be taken in dimension O(n)\bigO(\sqrt{n}), used in the code.

Goemans-Williamson rounding

We still need to turn vectors into a cut. Goemans and Williamson’s (1995) idea is simple: cut the sphere with a random hyperplane through the origin, assigning vertices according to which side their vectors fall on. With r∼N(0,I)\vb{r} \sim \Normal(\vb{0}, \mat{I}), set xi=sign⁡(r⊤vi)x_i = \operatorname{sign}(\vb{r}\T\vb{v}_i).

Proof

Let θij=arccos⁡(vi⊤vj)\theta_{ij} = \arccos(\vb{v}_i\T\vb{v}_j) be the angle between two vectors. Project r\vb{r} onto the plane spanned by vi\vb{v}_i and vj\vb{v}_j: the projection of an isotropic Gaussian is isotropic Gaussian in the plane, with direction uniform on the circle. Signs of r⊤vi\vb{r}\T\vb{v}_i and r⊤vj\vb{r}\T\vb{v}_j differ exactly when the line perpendicular to that projection separates vi\vb{v}_i from vj\vb{v}_j, which occurs when the direction falls into one of two opposite arcs of angle θij\theta_{ij} each, on a circle of 2π2\pi. Thus

P(xi≠xj)=θijπ.\Pr(x_i \ne x_j) = \frac{\theta_{ij}}{\pi}.

By linearity of expectation, E[cut]=∑i<jwij θij/π\E[\text{cut}] = \sum_{i<j} w_{ij}\,\theta_{ij}/\pi, while SDP=∑i<jwij (1−cos⁡θij)/2\text{SDP} = \sum_{i<j} w_{ij}\,(1 - \cos\theta_{ij})/2. Compare term by term: for every θ∈(0,π]\theta \in (0, \pi], θ/π≥αGW (1−cos⁡θ)/2\theta/\pi \ge \alpha_{\mathrm{GW}}\,(1 - \cos\theta)/2 with αGW\alpha_{\mathrm{GW}} the minimum of ratio 2θπ(1−cos⁡θ)\frac{2\theta}{\pi(1 - \cos\theta)} (for θ=0\theta = 0 both sides are 0). Multiply by wij≥0w_{ij} \ge 0 and sum. The second inequality is SDP≥MAXCUT\text{SDP} \ge \text{MAXCUT}. The minimum occurs where the derivative vanishes, giving tan⁡(θ/2)=θ\tan(\theta/2) = \theta, that is θ⋆≈2.331\theta^\star \approx 2.331 (about 133.6°133.6°), with value ≈0.87856\approx 0.87856.

∎

Two assumptions matter: wij≥0w_{ij} \ge 0 (a negative weight reverses termwise comparison), and the guarantee is in expectation: one hyperplane may give a worse cut, so in practice many are tried and the best retained. The value 0.8780.878 is also hard to improve: if the unique games conjecture holds, approximating MAXCUT within factor αGW+ε\alpha_{\mathrm{GW}} + \varepsilon is NP-hard, so no polynomial algorithm improves αGW\alpha_{\mathrm{GW}} unless P = NP (Khot, Kindler, Mossel and O’Donnell, 2007). It also certifies: since the SDP value upper-bounds MAXCUT, a cut of value cc and SDP bound ss guarantee at least c/sc/s of optimum without knowing it.

InteractiveCutting a graph with an SDP
0.800.800.800.800.8012345current cut: 4 of 5 edges
24−r
Cut size for 300 random hyperplanes
012345frequency
  • exact E[cut]\mathbb{E}[\text{cut}]
  • optimum
  • SDP bound
  • 0.878×0.878\times bound
  • side A
  • side B
The exact expectation 4.000 is at least 0.878×0.878\times 4.523 = 3.973, and the SDP bound is at least the optimum 4.
5
Random hyperplane
SDP bound4.523
Optimum (brute force)4
Current hyperplane cut4 of 5
Exact E[cut]\mathbb{E}[\text{cut}]4.000
Mean of 300 hyperplanes4.000
0.878×0.878 \times SDP bound3.973
Optimum / bound0.884
For a small graph (add or remove edges by clicking two vertices), the relaxation is solved and unit vectors appear on the sphere. Drag the hyperplane point to rotate it: each side of the sphere assigns vertices a color, and the resulting cut is counted. Readings compare, for your hyperplane, the SDP bound, brute-force optimum, exact expectation ∑wijθij/π\sum w_{ij}\theta_{ij}/\pi and mean of hundreds or thousands of random hyperplanes (the handle marks r\vb{r}, or −r-\vb{r} when r\vb{r} is behind the sphere: they define the same hyperplane). For the pentagon, how many edges can a hyperplane cut at most? What is the bound? Enable θij/π\theta_{ij}/\pi on edges to see the cutting probability of each. Try bipartite K3,3K_{3,3}: why is the relaxation exact here?

For the pentagon the relaxation places five vectors in a plane, 144°144° from their cycle neighbors: each edge contributes (1−cos⁡144°)/2≈0.9045(1 - \cos 144°)/2 \approx 0.9045 and the bound is 5×0.9045=(25+55)/8≈4.52255 \times 0.9045 = (25 + 5\sqrt{5})/8 \approx 4.5225. The maximum cut of a pentagon is 4 (an odd cycle cannot be bipartite: one edge always remains uncut). Here rounding is perfect: each edge is cut with probability 144/180=0.8144/180 = 0.8, expectation is 5×0.8=45 \times 0.8 = 4, and as no cut exceeds 4, every hyperplane cuts exactly 4 edges (as the interactive histogram shows). The gap is 4/4.5225≈0.8844/4.5225 \approx 0.884, just above the 0.8780.878 guarantee: the pentagon is among cases where the relaxation loses almost all the theory permits. Since weights are integers, the cut is integral and cannot exceed ⌊4.5225⌋=4\lfloor 4.5225 \rfloor = 4: the SDP bound certifies 4 is optimal without enumeration.

Implementation from scratch

First, manual modeling. An LP in matrix form with scipy.optimize.linprog: ℓ1\ell_1 regression and ℓ∞\ell_\infty minimax fitting via the lesson’s epigraph construction, versus least squares, on data with four outliers. Notice that no modeler translates anything: constraint matrices [A,−I;−A,−I][\mat{A}, -\mat{I}; -\mat{A}, -\mat{I}] are exactly −t≤Ax−b≤t-\vb{t} \le \mat{A}\vb{x} - \vb{b} \le \vb{t}.

[ ]l1 regression and l∞ fitting as linear programsBrowser
import numpy as np
from scipy.optimize import linprog
import matplotlib.pyplot as plt

def ajuste_l1(A, b):
    """min ||Ax - b||_1 como LP en (x, t): -t <= Ax - b <= t, minimizar sum(t)."""
    m, d = A.shape
    c = np.r_[np.zeros(d), np.ones(m)]
    G = np.block([[A, -np.eye(m)], [-A, -np.eye(m)]])
    h = np.r_[b, -b]
    res = linprog(c, A_ub=G, b_ub=h, bounds=[(None, None)] * d + [(0, None)] * m, method="highs")
    return res.x[:d], res.fun

def ajuste_linf(A, b):
    """min ||Ax - b||_inf como LP en (x, t): -t <= Ax - b <= t, minimizar t."""
    m, d = A.shape
    c = np.r_[np.zeros(d), 1.0]
    uno = np.ones((m, 1))
    G = np.block([[A, -uno], [-A, -uno]])
    h = np.r_[b, -b]
    res = linprog(c, A_ub=G, b_ub=h, bounds=[(None, None)] * d + [(0, None)], method="highs")
    return res.x[:d], res.fun

rng = np.random.default_rng(3)
m = 30
t = np.linspace(0, 10, m)
A = np.c_[np.ones(m), t]                       # modelo y = a + b t
y = 2 + 0.5 * t + 0.15 * rng.standard_normal(m)
y[[4, 11, 12, 25]] += [4.0, -3.5, 3.0, -4.0]   # cuatro valores atípicos

x2 = np.linalg.lstsq(A, y, rcond=None)[0]
x1, c1 = ajuste_l1(A, y)
xi, ci = ajuste_linf(A, y)
verdad = np.array([2.0, 0.5])

for nombre, x in [("mínimos cuadrados (l2)", x2), ("regresión l1 (LP)", x1), ("minimax l∞ (LP)", xi)]:
    r = A @ x - y
    print(f"{nombre:24s} a = {x[0]:6.3f}  b = {x[1]:6.3f}  error de parámetros = {np.linalg.norm(x - verdad):.3f}"
          f"   ||r||_1 = {np.abs(r).sum():6.2f}   ||r||_inf = {np.abs(r).max():5.2f}")

# estructura de vértice: cuántos residuos activos tiene cada solución
r1 = np.abs(A @ x1 - y)
ri = np.abs(A @ xi - y)
print("\nl1: residuos nulos =", int((r1 < 1e-8).sum()), "(= número de parámetros, d = 2)")
print("l∞: residuos iguales al máximo =", int((np.abs(ri - ci) < 1e-8).sum()), "(= d + 1 = 3)")

plt.scatter(t, y, color="gray", s=18, label="datos")
for nombre, x, estilo in [("l2", x2, "-"), ("l1", x1, "-"), ("l∞", xi, "--")]:
    plt.plot(t, A @ x, estilo, label=nombre)
plt.legend(); plt.xlabel("t"); plt.ylabel("y"); plt.show()

Each solution is best according to its own norm: ℓ1\ell_1 has the lowest ∥r∥1\norm{\vb{r}}_1 (17.65 versus 21.59 for least squares) and ℓ∞\ell_\infty the lowest ∥r∥∞\norm{\vb{r}}_\infty (3.32 versus 3.65 for least squares and 3.97 for ℓ1\ell_1). But for the important question, which line recovers true parameters (2,0.5)(2, 0.5)?, ℓ1\ell_1 approaches an error of 0.040.04, whereas least squares gives 0.450.45 and minimax 1.161.16. The last two lines confirm the vertex theorem: 2 zero residuals for ℓ1\ell_1 and 3 at the maximum for ℓ∞\ell_\infty.

Second, MAXCUT relaxation and rounding without a modeler. The relaxation is solved by coordinate ascent on spheres (Wang, Chang and Kolter’s mixing method): holding other vectors fixed, vi\vb{v}_i that most increases objective ∑jwij(1−vi⊤vj)/2\sum_j w_{ij}(1 - \vb{v}_i\T\vb{v}_j)/2 is the negative of normalized vector ∑jwijvj\sum_j w_{ij}\vb{v}_j, an exact and cheap step. With dimension d(d+1)/2>nd(d+1)/2 > n the factored problem has no spurious local minima for almost every cost matrix (Boumal, Voroninski and Bandeira, 2016), and in practice converges to the SDP global optimum.

[ ]MAXCUT: unit-vector SDP relaxation and Goemans-Williamson roundingBrowser
import itertools
import numpy as np

def grafo_aleatorio(n, p, rng):
    W = np.triu((rng.random((n, n)) < p).astype(float), 1)
    return W + W.T

def corte(W, lado):
    """Valor del corte: suma de pesos de las aristas cuyos extremos tienen distinto signo."""
    return 0.25 * np.sum(W * (1 - np.outer(lado, lado)))

def fuerza_bruta(W):
    n = len(W)
    mejor = max(itertools.product([1, -1], repeat=n - 1), key=lambda s: corte(W, np.r_[1, s]))
    return corte(W, np.r_[1, mejor])

def relajacion_sdp(W, dim=None, barridos=300, semilla=0):
    """Relajación SDP de MAXCUT por vectores unitarios (método de mezcla).
    Cada fila v_i de V es un vector unitario; maximizamos sum_{i<j} W_ij (1 - v_i.v_j)/2.
    Con v_j fijos, el mejor v_i es -normalizado(sum_j W_ij v_j): un paso exacto por coordenada."""
    n = len(W)
    dim = dim or int(np.ceil(np.sqrt(2 * n))) + 1
    rng = np.random.default_rng(semilla)
    V = rng.standard_normal((n, dim))
    V /= np.linalg.norm(V, axis=1, keepdims=True)
    for _ in range(barridos):
        for i in range(n):
            g = W[i] @ V
            norma = np.linalg.norm(g)
            if norma > 1e-12:
                V[i] = -g / norma
    cota = 0.25 * np.sum(W * (1 - V @ V.T))
    return V, cota

def redondeo(V, W, n_intentos, rng):
    """Goemans-Williamson: lado_i = signo(r . v_i) con r gaussiano; devuelve los valores de todos los cortes."""
    R = rng.standard_normal((n_intentos, V.shape[1]))
    lados = np.sign(R @ V.T)
    lados[lados == 0] = 1
    return np.array([corte(W, s) for s in lados])

# 1. Pentágono: la cota SDP es 4.5225, el óptimo es 4
C5 = np.zeros((5, 5))
for i in range(5):
    C5[i, (i + 1) % 5] = C5[(i + 1) % 5, i] = 1
V, cota = relajacion_sdp(C5)
print(f"C5: cota SDP = {cota:.4f}   (25 + 5 sqrt 5)/8 = {(25 + 5 * 5 ** 0.5) / 8:.4f}   óptimo = {fuerza_bruta(C5):.0f}")

# 2. Grafos aleatorios: ¿cuánto vale el redondeo?
rng = np.random.default_rng(7)
print("\n  n  aristas  cota SDP  óptimo  media redondeo  mejor de 100  media/cota  mejor/óptimo")
for n in (8, 10, 12, 14):
    W = grafo_aleatorio(n, 0.5, rng)
    V, cota = relajacion_sdp(W)
    opt = fuerza_bruta(W)
    cortes = redondeo(V, W, 2000, rng)
    print(f"{n:3d}  {int(W.sum() / 2):7d}  {cota:8.3f}  {opt:6.0f}  {cortes.mean():14.3f}  {cortes[:100].max():12.0f}  {cortes.mean() / cota:10.3f}  {cortes[:100].max() / opt:12.3f}")

The pentagon bound matches the closed formula, and on the four random graphs mean rounding is between 93 % and 99.5 % of the bound, well above worst-case 0.8780.878, while the best of 100 hyperplanes gives the exact optimum on all four. The 0.8780.878 guarantee concerns the worst possible graph; on ordinary graphs rounding is much better.

With libraries: CVXPY

With CVXPY, everything above takes a few lines. The cell is local because CVXPY and its solvers are installed in the lab environment, not Pyodide (execution is on CPU, with minimal sizes). It solves a QP (portfolio), an SOCP (norm-constrained least squares), two SDPs (the pentagon MAXCUT relaxation and nuclear-norm matrix completion), shows what the solver sees with get_problem_data, and compares three solvers.

[ ]CVXPY in practice: QP, SOCP, SDP and conic formLocal GPU
import time
import numpy as np
import cvxpy as cp

rng = np.random.default_rng(0)

# 1. QP: cartera media-varianza sin ventas en corto
n = 8
F = rng.standard_normal((n, 3))
Sigma = F @ F.T / 3 + 0.1 * np.eye(n)
mu = 0.05 + 0.1 * rng.random(n)
w = cp.Variable(n)
riesgo = cp.quad_form(w, cp.psd_wrap(Sigma))
qp = cp.Problem(cp.Minimize(riesgo - 0.5 * mu @ w), [cp.sum(w) == 1, w >= 0])
qp.solve()
print("QP  ", qp.status, f"valor = {qp.value:.5f}", "pesos =", np.round(w.value, 3))
print("    problema DCP:", qp.is_dcp(), " curvatura del objetivo:", qp.objective.expr.curvature)

# 2. SOCP: mínimos cuadrados con restricción de norma
m, d = 40, 10
A = rng.standard_normal((m, d))
b = A @ rng.standard_normal(d) + 0.5 * rng.standard_normal(m)
x = cp.Variable(d)
socp = cp.Problem(cp.Minimize(cp.norm(A @ x - b, 2)), [cp.norm(x, 2) <= 1])
socp.solve()
print("\nSOCP", socp.status, f"valor = {socp.value:.5f}   ||x|| = {np.linalg.norm(x.value):.5f}")

# 3. SDP: la relajación de MAXCUT del pentágono
Wc = np.zeros((5, 5))
for i in range(5):
    Wc[i, (i + 1) % 5] = Wc[(i + 1) % 5, i] = 1
X = cp.Variable((5, 5), PSD=True)
sdp = cp.Problem(cp.Maximize(0.25 * cp.sum(cp.multiply(Wc, 1 - X))), [cp.diag(X) == 1])
sdp.solve()
print("\nSDP MAXCUT C5:", sdp.status, f"cota = {sdp.value:.5f}   rango numérico de X = {np.linalg.matrix_rank(X.value, tol=1e-6)}")

# 4. SDP: completado de matrices de rango 2 por norma nuclear
k = 20
M = rng.standard_normal((k, 2)) @ rng.standard_normal((2, k))
print()
for frac in (0.3, 0.6):
    mask = rng.random((k, k)) < frac
    Z = cp.Variable((k, k))
    completar = cp.Problem(cp.Minimize(cp.normNuc(Z)), [cp.multiply(mask, Z) == mask * M])
    completar.solve()
    err = np.linalg.norm(Z.value - M) / np.linalg.norm(M)
    print(f"Norma nuclear: {mask.mean():.0%} de entradas observadas, error relativo = {err:.1e}, rango de la solución = {np.linalg.matrix_rank(Z.value, tol=1e-5)}")

# 5. Qué ve el solver: la forma cónica
for nombre, p in (("SOCP", socp), ("SDP de MAXCUT", sdp)):
    datos, _, _ = p.get_problem_data(cp.CLARABEL)
    dims = datos["dims"]
    print(f"\n{nombre} canonicalizado: {datos['c'].size} variables, {datos['A'].shape[0]} filas, "
          f"igualdades: {dims.zero}, desigualdades lineales: {dims.nonneg}, conos de segundo orden: {dims.soc}, conos PSD: {dims.psd}")

# 6. Tres solvers sobre el mismo QP, comparados con la referencia más exacta
referencia = None
print("\nsolver      tiempo (ms)   |valor - referencia|")
for s in (cp.CLARABEL, cp.OSQP, cp.SCS):
    t0 = time.perf_counter()
    qp.solve(solver=s)
    ms = 1000 * (time.perf_counter() - t0)
    if referencia is None:
        referencia = qp.value
    print(f"{s:10s}  {ms:10.1f}   {abs(qp.value - referencia):.1e}   estado: {qp.status}")
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

Several observations. The QP is recognized as DCP and the objective classified as convex. The SOCP reaches the ball’s boundary (∥x∥2=1\norm{\vb{x}}_2 = 1): the unconstrained optimum was outside, so the constraint is active. The pentagon SDP yields 4.522544.52254, matching the closed formula and from-scratch cell, and matrix X\mat{X} has rank 2, the planar structure seen on the sphere. Matrix completion illustrates something important: with 28 % observed entries nuclear norm does not recover the matrix (relative error 0.32, solution rank 8), while with 63 % it recovers it to solver error (rank 2, error 7×10−87\times 10^{-8}). The relaxation is exact only with enough data (for a rank-rr k×kk \times k matrix satisfying incoherence assumptions and randomly observed entries, on the order of r kr\,k entries suffices up to logarithmic factors: Candès and Recht, 2009, refined by Candès and Tao, 2010, and Recht, 2011); below that threshold it returns a high-rank matrix that is not the true one. Canonicalization shows conic form: the SOCP has a second-order cone of dimension 41 (=m+1= m + 1, for the residual norm) and another of dimension 11 (=d+1= d + 1, for ∥x∥2≤1\norm{\vb{x}}_2 \le 1), while the MAXCUT SDP has a semidefinite cone of order 5, one variable per upper-triangular entry of X\mat{X} (1515), and five equalities for diag⁡(X)=1\diag(\mat{X}) = \vb{1}. On a small problem all three solvers agree within tolerance and take milliseconds; the difference appears at large scale (precise interior point with factorizations, lighter but less accurate ADMM).

Common mistakes

Exercises

QuizWhich rung is each problem on?
Classify each problem by its lowest rung (LP, QP, SOCP or SDP), in this order: (a) minimize ∥Ax−b∥1\norm{\mat{A}\vb{x} - \vb{b}}_1; (b) minimize ∥Ax−b∥2\norm{\mat{A}\vb{x} - \vb{b}}_2 subject to ∥x∥2≤1\norm{\vb{x}}_2 \le 1; (c) minimize λmax⁡(A0+∑ixiAi)\lambda_{\max}(\mat{A}_0 + \sum_i x_i\mat{A}_i); (d) minimize x⊤Px+q⊤x\vb{x}\T\mat{P}\vb{x} + \vb{q}\T\vb{x} with P⪰0\mat{P} \succeq \mat{0}, subject to Gx≤h\mat{G}\vb{x} \le \vb{h}.
QuizConvex as written?
Which of these problems are convex optimization problems as written (using this lesson's definition)?

More than one answer may be correct.

QuizThe condition with active constraints
In min⁡(x−3)2\min (x - 3)^2 subject to x≤1x \le 1, the optimum is x⋆=1x^\star = 1, with f0′(1)=−4≠0f_0'(1) = -4 \ne 0. What is the correct reading of ∇f0(x⋆)⊤(y−x⋆)≥0\grad f_0(x^\star)\T(y - x^\star) \ge 0 for every feasible yy?
NumericSolve an LP by hand
Maximize 3x+2y3x + 2y subject to x+y≤4x + y \le 4, x+3y≤6x + 3y \le 6, x≥0x \ge 0, y≥0y \ge 0. What is the optimal value?
NumericThe margin of a robust constraint
Constraint a⊤x≤β\vb{a}\T\vb{x} \le \beta must hold for every a=aˉ+Pu\vb{a} = \bar{\vb{a}} + \mat{P}\vb{u} with ∥u∥2≤1\norm{\vb{u}}_2 \le 1, aˉ=(1,2)\bar{\vb{a}} = (1, 2) and P=diag⁡(1,2)\mat{P} = \diag(1, 2). For x=(1,1)\vb{x} = (1, 1), what is the supremum of a⊤x\vb{a}\T\vb{x} over that ellipsoid? This is the smallest β\beta for which x\vb{x} is robustly feasible.
NumericThe pentagon SDP bound
In the MAXCUT SDP relaxation for cycle C5C_5 (five vertices, five edges of weight 1), optimal vectors lie in a plane and vectors of adjacent cycle vertices form an angle of 144°144° (=4π/5)(= 4\pi/5). What is the bound ∑i<jwij(1−vi⊤vj)/2\sum_{i<j} w_{ij}(1 - \vb{v}_i\T\vb{v}_j)/2?
ProofMinimizing the $\ell_\infty$ norm is an LP
Prove: For A∈Rm×d\mat{A} \in \R^{m \times d} and b∈Rm\vb{b} \in \R^m, the problem min⁡x∥Ax−b∥∞\min_{\vb{x}} \norm{\mat{A}\vb{x} - \vb{b}}_\infty is equivalent to the linear program min⁡x,tt\min_{\vb{x}, t} t subject to −t1≤Ax−b≤t1-t\vb{1} \le \mat{A}\vb{x} - \vb{b} \le t\vb{1}.
0
Let r(x)=Ax−b\vb{r}(\vb{x}) = \mat{A}\vb{x} - \vb{b} and recall that ∥r∥∞=max⁡i∣ri∣\norm{\vb{r}}_\infty = \max_i \abs{r_i}.

Step 1 of 4. What does ∥r∥∞≤t\norm{\vb{r}}_\infty \le t mean in terms of rir_i?

CodeGoemans-Williamson rounding
Implement maxcut_round(V, W, n_trials=200, seed=0). It receives V of shape (n, d) with unit rows (vectors of the SDP relaxation) and symmetric weight matrix W of shape (n, n), with nonnegative weights and zero diagonal. Generate n_trials Gaussian directions using np.random.default_rng(seed) (one vector r of dimension d per trial), assign each vertex side +1 if r @ V[i] >= 0 and -1 otherwise, calculate each trial's cut value and return (mejor_valor, mejor_lado), where mejor_lado is an array of n values in {+1, -1}. The cut value is the sum of weights of edges whose endpoints lie on different sides: 0.25 * sum_ij W_ij * (1 - lado_i * lado_j).
import numpy as np

def maxcut_round(V, W, n_trials=200, seed=0):
  """Redondeo de Goemans-Williamson: devuelve (mejor_valor, mejor_lado)."""
  n = V.shape[0]
  # tu código: n_trials direcciones gaussianas, signo de r . v_i, valor de cada corte y el mejor
  return 0.0, np.ones(n)
Shift+Enter to run
QuizWhy CVXPY rejects this expression
When minimizing cp.sqrt(cp.sum_squares(x) + 1), CVXPY raises a DCP error. Why, and which accepted rewrite represents the same function?
QuizWhat the MAXCUT relaxation says
Which statements about the MAXCUT semidefinite relaxation and Goemans-Williamson rounding are true?

More than one answer may be correct.

Summary

Key idea
A problem is convex when objective, inequalities and equalities satisfy the definition, and then every local minimum is global; convex optimization engineering consists of reformulating to fit an LP, QP, SOCP or SDP (increasingly broad cones), then letting a conic solver guided by DCP rules solve it with guarantees; when the problem is nonconvex, a convex relaxation gives a bound and, with rounding, an approximate solution.
  • Convex in standard form: f0,fif_0, f_i convex and equalities affine. Local optimum == global, and x⋆\vb{x}^\star is optimal if and only if ∇f0(x⋆)⊤(y−x⋆)≥0\grad f_0(\vb{x}^\star)\T(\vb{y} - \vb{x}^\star) \ge 0 for every feasible y\vb{y}: the gradient hyperplane supports the feasible set.
  • Reformulation: epigraph form (linear objective, complexity in constraints), slacks (only for affine constraints), equality elimination, sign splitting. A min⁡max⁡\min\max of affine functions is an LP.
  • LP: optimum at a vertex of a polyhedron without lines, or unbounded or infeasible; cost parallel to a face yields infinitely many optima. The ℓ1\ell_1 and ℓ∞\ell_\infty norms are LPs and their solutions interpolate dd and d+1d + 1 data points.
  • QP and SOCP: 12x⊤Px\tfrac12\vb{x}\T\mat{P}\vb{x} with P⪰0\mat{P} \succeq \mat{0} (the equality case is a linear KKT system); cone ∥y∥2≤s\norm{\vb{y}}_2 \le s includes QPs and models robust constraints with ellipsoidal uncertainty.
  • SDP: linear matrix inequalities; λmax⁡(M)≤t  ⟺  tI−M⪰0\lambda_{\max}(\mat{M}) \le t \iff t\mat{I} - \mat{M} \succeq \mat{0}, and the Schur complement gives LP ⊂\subset QP ⊂\subset SOCP ⊂\subset SDP. More expressive and more expensive: use the lowest rung.
  • DCP and CVXPY: curvature, sign and monotonicity per atom, with a composition rule; this is sufficient (sqrt(1 + x^2) is rejected, norm([1, x]) accepted). The problem is canonicalized to conic form and a solver solves it; check status and residuals.
  • Relaxations: p~⋆≤p⋆\tilde{p}^\star \le p^\star. MAXCUT with unit vectors and hyperplane rounding gives E[cut]≥0.878 SDP\E[\text{cut}] \ge 0.878\,\text{SDP}, and the SDP bound certifies any cut’s quality.