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 instead of gives a line barely moved by outliers. It is a linear program.
- Portfolios. Choosing weights that minimize risk 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 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 and equality constraints , 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 defines a sphere, which is not convex; is the convex ball. An equality is equivalent to the two inequalities and , and only when is both convex and concave, that is affine, can both be convex.
- Form matters, not just the set. The problem “minimize subject to ” is not convex because constraint has a concave, not convex, function. But a nonconvex formulation can describe a convex set: 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 be a local minimum: it is feasible and there is an such that for all feasible with . Suppose for a contradiction there is a feasible with . For , is feasible by convexity of the feasible set, and convexity of gives
Since , choose so lies in the ball of radius and improves on . This contradicts local minimality. The optimal set is a sublevel set of a convex function within a convex set, hence convex. And if were strictly convex and there were two distinct optima , their midpoint would be feasible with .
∎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, : the tangent lies below the function.
Proof
() By the first-order condition, for every feasible . () Suppose is optimal but there is with . The point is feasible for and , so for small . Contradiction.
∎Remember the geometric reading: is the steepest descent direction, and the condition says no feasible direction forms an acute angle with it. Thus hyperplane supports the feasible set at (the supporting hyperplane theorem in action). Three direct consequences:
- Unconstrained (). Taking gives , so . This is the first-order condition of lesson 1, now sufficient, not only necessary.
- Equalities only (). Differences span the nullspace of , which is a subspace, and a linear functional that is on a subspace vanishes there. Thus , meaning : there is with . This is a Lagrange multiplier, studied in lesson 5.
- Nonnegative orthant (). With we obtain , and with , . Since , the sum of nonnegative terms is both and : each term vanishes. This is complementary slackness in its simplest form: in each coordinate either the constraint is active () 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.
| Transformation | Before | After | When convexity is preserved |
|---|---|---|---|
| Epigraph form | subject to | always, if is convex | |
| Slack variables | , | only if is affine | |
| Eliminate equalities | always (with a basis of ) | ||
| Split sign | free | , | always, in linear problems |
| Monotone objective function | if 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 on , epigraph form is
Proof
For fixed , values satisfying form a ray and the least is . Minimizing first over and then over (partial minimization does not change the joint optimum) gives . If is convex, 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 are parallel hyperplanes. Minimizing means moving a hyperplane in direction 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.
What you just saw is a theorem. But it must be stated carefully, since not every polyhedron has vertices (a strip in 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): . If any ray satisfies , then for every and the cost tends to : unbounded. If all satisfy , every can be written with and , and
The minimum of the vertex values is attainable and bounds the entire polyhedron from below: it is the optimum, attained at a vertex. The optimal set is , and since contains , that intersection is a face.
∎The trichotomy (infeasible, unbounded or attained optimum) holds for every LP, including when the polyhedron contains lines: decompose into a polyhedron without lines plus its lineality space, on which must vanish for the problem to be bounded. What may be absent without the assumption is a vertex: in the strip above, minimizing 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 constraints in there are up to 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 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 and norms are linear programs
A norm is not linear, but and are maxima and sums of absolute values of affine functions, and epigraph form turns them into LPs. For the fit with , introduce a variable for each residual with , that is, :
This LP has variables and inequalities. Equivalence follows from the epigraph theorem applied term by term: for fixed , the least feasible is attained at . For , one variable suffices to bound all residuals, , 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 has full column rank: a line in direction would require and to satisfy the homogeneous constraints , forcing and , that is . By the fundamental theorem there is a vertex optimum. In a vertex has linearly independent active constraints. For , each index contributes at most two active constraints, and only if (if only one of , can be active). With zero residuals there are at most active constraints, and forces . For , in a vertex has active constraints, each of the form , and with one index cannot have both, so there are distinct indices.
∎Thus the 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 for certain if and if , so a nonzero residual contributes only its sign and a large one pushes as much as a small one. By contrast weights each residual by size. And is the opposite: a line watching only the worst datum, with a band supported by points.
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 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 be semidefinite. Common applications:
- Constrained least squares. is quadratic with , so adding bounds or leaves a QP. So does lasso, , after sign splitting and adding the variables from the preceding LP.
- Projection onto a polyhedron. subject to is the Euclidean projection of onto the polyhedron.
- Markowitz portfolios. With weights , expected returns and covariance : subject to , . Parameter 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 derived above becomes linear, because . The problem reduces to solving a linear system, the KKT system:
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: with is convex but has a quadratic constraint. The tool is the second-order cone of the previous lesson:
SOCPs contain convex QPs, and the proof is an algebraic identity worth memorizing.
Proof
() The inequality on the right requires , and squaring gives . Since , this is equivalent to . () If , then , so , squaring is an equivalence, and the same calculation runs backward.
∎The usefulness of second-order cones appears in robust optimization. Imagine an LP subject to where vector is not exactly known, only that it lies in the ellipsoid . Requiring the constraint for every seems to require infinitely many constraints. But
by Cauchy-Schwarz (the supremum is attained with aligned with ). The robust constraint is therefore one SOCP constraint, : the margin subtracted from is proportional to the norm of measured by the uncertainty. This is the same pattern as the portfolio risk constraint , 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 with unknown perturbation of spectral norm , the worst-case residual is
The inequality is the triangle inequality with , and equality is attained with , where is the normalized residual (if 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 subject to , 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 , the cone of symmetric matrices with nonnegative eigenvalues.
An LMI is in fact infinitely many linear inequalities at once ( for every ), explaining its expressive power. Three identities yield almost all applications.
The maximum eigenvalue. Since eigenvalues of are , . Thus, for a matrix depending affinely on , ,
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 , then (the Schur complement). With , column and , for ,
because the complement is , whose smallest eigenvalue is . The equivalence also holds for : with both sides force (a semidefinite matrix with zero diagonal is zero), and with 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 QP SOCP SDP. Why not always solve as SDP? Cost: an LMI of order adds 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 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: if and only if there are with and (Recht, Fazel and Parrilo, 2010). With it, matrix completion (filling unknown entries of an assumed low-rank matrix) is the SDP “minimize subject to 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.
One observation about the ladder: it is not a list of four different things but an expansion of the cone in which the problem lives. After introducing auxiliary variables, every problem in this lesson can be written as
where is a product of orthants (LP), second-order cones (SOCP) and semidefinite cones (SDP), and, if needed, the exponential cone (for and ). 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 is convex and nondecreasing and is convex, then : the first inequality uses convexity of and the fact is nondecreasing; the second uses convexity of . The remaining cases are analogous.
A DCP problem minimizes a convex expression (or maximizes a concave one) subject to “convex 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.
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: is the Euclidean norm of vector and therefore convex, but written as sqrt(1 + x^2) it composes (concave and increasing) with (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 (concave of convex); x**2 / y is written quad_over_lin(x, y); and the concave geometric mean 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, is a second-order constraint and is an LMI. CVXPY traverses the tree replacing each atom with an auxiliary variable plus the corresponding conic constraints, ending with the conic problem above. For example, becomes
with a second-order cone of dimension and 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 with (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 with weights (a graph without loops, ), 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 : edge crosses if and only if , and is 1 if it crosses, 0 otherwise. Then
Relax each to a unit vector , , and replace the product with the inner product:
Since are a special case (), this is a relaxation: (for maximization the bound is upper). Why is it called “semidefinite”? With , Gram matrix (with as columns) satisfies , , and the objective is linear in :
where is the Laplacian. The original problem is exactly the same with the extra constraint (since ). Removing the rank constraint, the nonconvex part, yields the relaxation: (the elliptope, the set of correlation matrices) is convex and contains every . A result by Barvinok and Pataki guarantees an optimum of rank with , that is, , so vectors can be taken in dimension , 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 , set .
Proof
Let be the angle between two vectors. Project onto the plane spanned by and : the projection of an isotropic Gaussian is isotropic Gaussian in the plane, with direction uniform on the circle. Signs of and differ exactly when the line perpendicular to that projection separates from , which occurs when the direction falls into one of two opposite arcs of angle each, on a circle of . Thus
By linearity of expectation, , while . Compare term by term: for every , with the minimum of ratio (for both sides are 0). Multiply by and sum. The second inequality is . The minimum occurs where the derivative vanishes, giving , that is (about ), with value .
∎Two assumptions matter: (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 is also hard to improve: if the unique games conjecture holds, approximating MAXCUT within factor is NP-hard, so no polynomial algorithm improves unless P = NP (Khot, Kindler, Mossel and O’Donnell, 2007). It also certifies: since the SDP value upper-bounds MAXCUT, a cut of value and SDP bound guarantee at least of optimum without knowing it.
For the pentagon the relaxation places five vectors in a plane, from their cycle neighbors: each edge contributes and the bound is . 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 , expectation is , and as no cut exceeds 4, every hyperplane cuts exactly 4 edges (as the interactive histogram shows). The gap is , just above the 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 : the SDP bound certifies 4 is optimal without enumeration.
Implementation from scratch
First, manual modeling. An LP in matrix form with scipy.optimize.linprog: regression and minimax fitting via the lesson’s epigraph construction, versus least squares, on data with four outliers. Notice that no modeler translates anything: constraint matrices are exactly .
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: has the lowest (17.65 versus 21.59 for least squares) and the lowest (3.32 versus 3.65 for least squares and 3.97 for ). But for the important question, which line recovers true parameters ?, approaches an error of , whereas least squares gives and minimax . The last two lines confirm the vertex theorem: 2 zero residuals for and 3 at the maximum for .
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, that most increases objective is the negative of normalized vector , an exact and cheap step. With dimension 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.
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 , while the best of 100 hyperplanes gives the exact optimum on all four. The 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.
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}")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 (): the unconstrained optimum was outside, so the constraint is active. The pentagon SDP yields , matching the closed formula and from-scratch cell, and matrix 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 ). The relaxation is exact only with enough data (for a rank- matrix satisfying incoherence assumptions and randomly observed entries, on the order of 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 (, for the residual norm) and another of dimension 11 (, for ), while the MAXCUT SDP has a semidefinite cone of order 5, one variable per upper-triangular entry of (), and five equalities for . 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
More than one answer may be correct.
Step 1 of 4. What does mean in terms of ?
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)cp.sqrt(cp.sum_squares(x) + 1), CVXPY raises a DCP error. Why, and which accepted rewrite represents the same function?More than one answer may be correct.
Summary
- Convex in standard form: convex and equalities affine. Local optimum global, and is optimal if and only if for every feasible : 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 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 and norms are LPs and their solutions interpolate and data points.
- QP and SOCP: with (the equality case is a linear KKT system); cone includes QPs and models robust constraints with ellipsoidal uncertainty.
- SDP: linear matrix inequalities; , and the Schur complement gives LP QP SOCP 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: . MAXCUT with unit vectors and hyperplane rounding gives , and the SDP bound certifies any cut’s quality.