Interior-point methods
Explain the internals of solvers for LP, QP, SOCP and SDP: logarithmic barrier, central path and Newton barrier method. Introduce self-concordance and its problem-independent complexity bounds, and the primal-dual method used by solvers such as Clarabel and HiGHS.
After this lesson you can
- Construct the logarithmic barrier for inequality constraints and derive the central path.
- Use duality to prove a central-path point at parameter t is m/t-suboptimal.
- Implement the barrier method with phase I and domain-preserving damped Newton.
- Define self-concordance and explain the Newton iteration bound independent of conditioning.
- Implement a primal-dual interior-point method for LP and compare with scipy.optimize.linprog.
Before you start
Motivation: what a solver does when you call CVXPY
You write a portfolio problem in ten lines of CVXPY, call prob.solve(verbose=True), and a fraction of a second later see a table with twenty rows: one per iteration, with primal cost, dual cost, their difference, and two residuals falling from to . The problem had thousands of variables and constraints, yet the row count barely depends on them: double the size and hardly any rows appear.
Behind the table is an interior-point method. CVXPY rewrites your model as a conic convex problem (an LP, QP, SOCP or SDP, as in lesson 4) and passes it to a solver such as Clarabel, MOSEK or HiGHS. They do, with variations, the same:
- Replace inequality constraints with a barrier infinite at the boundary, making the problem smooth and unconstrained apart from equalities.
- Solve that smooth problem with Newton’s method, converging in a handful of steps.
- Gradually reduce barrier weight, following a curve of approximate solutions, the central path, to the optimum.
- At each iteration they know exactly how far they remain: they carry primal and dual points whose difference certifies suboptimality.
This lesson builds that machinery from scratch: logarithmic barrier, central path and its certificate, barrier method with phase I, self-concordance theory (explaining why Newton iteration count is independent of conditioning), and the primal-dual method real solvers use. You will be able to read that table, know when to trust status: optimal, and write an LP solver matching HiGHS in about thirty lines.
Simplex versus interior point: a complexity history
An LP reaches its optimum at a vertex of the feasible polyhedron. Dantzig’s (1947) simplex method moves along edges from vertex to vertex, improving cost each jump. It is extremely fast in practice, but in 1972 Klee and Minty constructed distorted dimension- cubes where Dantzig’s pivot rule visits all vertices. Such examples are known for nearly every proposed pivot rule, and whether a rule with polynomially many steps exists remains open.
Khachiyan resolved whether linear programming is in P in 1979 with the ellipsoid method: polynomial in input bit count , but too slow in practice to compete with simplex. In 1984 Karmarkar published a “projective” algorithm using arithmetic operations, competitive on large problems. Two years later Gill, Murray, Saunders, Tomlin and Wright showed it equivalent to a logarithmic barrier method with projected Newton, a 1960s idea (Frisch, Fiacco and McCormick) abandoned for numerical issues. Renegar (1988) gave the first path-following method with iterations, Kojima, Mizuno and Yoshise (1989) formulated primal-dual methods, Mehrotra (1992) added the predictor-corrector used by most current codes, and Nesterov and Nemirovskii (1994) used self-concordance to explain why it works and extend it to SOCP and SDP.
Both worlds coexist. Interior point often wins on large sparse LPs; simplex yields exact vertex solutions and warm-starts well, indispensable in integer programming branch-and-bound. Many solvers run interior point then a crossover to a vertex. SOCP and SDP have no simplex: interior point is the method.
The logarithmic barrier
Start with a convex inequality-constrained problem,
with convex and twice differentiable, of rank , attained optimum and a strictly feasible point (Slater’s condition, ensuring strong duality). Equalities do not trouble Newton, handled by a linear KKT system; inequalities do, introducing combinatorial choices (which constraints are active) no second-order method sees.
Hide inequalities in the objective. With indicator if and if , the problem is equivalent to minimizing with . The indicator is nondifferentiable, but can be approximated by a smooth function also diverging at the boundary:
with . It is convex, increasing and tends to as ; as grows it flattens for and approaches the indicator.
is convex because is convex and increasing and each is convex. Its derivatives are
For an LP in inequality form, , and with slacks everything is written with matrix products:
The Hessian sums outer products weighted by : near-active constraints dominate curvature. This geometry deforms in the next figure: far from the boundary the barrier is nearly flat; near an edge its curvature grows without bound normally and barely tangentially.
The central path and the certificate
For each , let minimize with (assume it exists uniquely; existence follows, for example, when the feasible set is bounded because tends to at the boundary; uniqueness also needs strictly convex on , as in an LP with bounded polyhedron).
For an LP, centrality is force balance: . The objective pulls with constant force ; each constraint pushes inward with force , magnitude , exactly the inverse distance from to its hyperplane. With small the barrier wins and the point stays central; with large it approaches the boundary until nearly active constraints balance the pull.
A free dual point
Centrality resembles stationarity of a Lagrangian. Divide by and define
Then : minimizes Lagrangian , convex in because . Thus we have a dual feasible point and evaluate its dual function without another solve.
The short proof is reconstructed in the final guided exercise; the missing ingredient is weak duality, . The bound depends on neither data, dimension , nor conditioning; only constraint count. To guarantee suboptimality , center at .
Perturbed KKT conditions
Another reading of the central path generalizes to primal-dual methods. The original problem’s KKT conditions are primal and dual feasibility, stationarity and complementary slackness . A point lies on the central path iff exist with
These are KKT with complementary slackness replaced by : each constraint contributes exactly to the gap, totaling . As we recover KKT. Primal-dual methods attack this system directly.
Actual suboptimality is smaller than the bound
The figure shows something the bound does not: if the optimal vertex is nondegenerate (exactly active constraints) and strict complementarity holds ( for all of them), actual LP central-path suboptimality is almost exactly at large , not . To see why, let be the dual optimum, with and outside active set of optimal vertex . Then
On the central path, and since the dual solution is unique (guaranteed by vertex nondegeneracy), . Thus . Inactive constraints also contribute each to gap , but that part is dual-side slack: . The code cell checks this for an LP with and .
The barrier method
The theorem suggests a one-step algorithm: center at . Theoretically valid, but with huge the centering problem is badly conditioned (the barrier only matters within of the boundary), and Newton starting far away needs many damped steps. Follow the central path in stages, using each center to start the next.
Each centering uses lesson 13’s damped Newton with two special details. The equality-constrained Newton step solves the KKT system
and the stopping criterion uses Newton decrement , affine invariant. The second detail is domain: backtracking starts with a full step and must first shrink it until strictly feasible, only then checking Armijo. Evaluating outside its domain makes of a negative number nan; since nan > a is false, Armijo comparison “accepts” it. In an LP the maximum step inside the domain is closed-form, , and one starts at a fraction, e.g. 99%.
Stage count and factor
After initial centering at , stage centers at , so the method finishes after
updates of , plus initial centering. With , , and there are updates and nine centerings. Large reduces stages, but each starts farther from its target and needs more Newton steps. Small gives one- or two-step centerings but many stages. Where is the balance?
The right curve is the practical lesson: except when is very close to 1, total work is nearly flat over a huge range. With between 10 and 200 the method needs 35–60 total Newton iterations, and tripling constraints adds at most about fifteen (1–14 depending on ). Large- centerings cost more but not proportionally to : Newton from the prior center soon reaches its quadratic phase. Theory below is much more pessimistic and recommends , giving the polynomial guarantee rather than the practical choice.
Phase I: finding a strictly feasible point
The method must start inside ‘s domain. If no such point is known, solve another convex problem for which one is known: phase I:
For any with (e.g. the minimum-norm solution), pair with is strictly feasible, so solve by the same barrier method. If its optimum is negative, the original is strictly feasible and stopping as soon as suffices; phase I need not finish. If , the original is infeasible and the phase-I dual gives a certificate (an alternative from the duality lesson). If , no strictly feasible points exist (though feasible ones may) and the barrier method cannot be applied unchanged. A useful variant minimizes the sum of violations, with and : when infeasible, it leaves many constraints satisfied and identifies incompatible ones.
Self-concordance and complexity
Lesson 13 bounded damped Newton iterations by , with depending on strong convexity, Hessian Lipschitz constant and a Hessian upper bound. These constants are disastrous for the barrier: near its boundary ‘s Hessian and Lipschitz constant explode. Yet Newton is affine invariant, so its behavior cannot depend on them. We need an affine-invariant hypothesis.
Why these exponents? Reparameterize : and , so ratio is unchanged: the definition is affine invariant, like Newton. Constant 2 normalizes the fundamental example to equality. Geometrically, the third derivative measures curvature change, and the condition says curvature changes slowly on its own scale, natural length .
Examples and counterexamples:
- Linear and convex quadratic: . Self-concordant.
- : and , so . Equality holds.
- on : self-concordant (arises adding a barrier to maximum-entropy problems).
- is not: fails for . on is not either: fails for .
Three calculus rules make the class huge: self-concordance is preserved by multiplication by , adding two self-concordant functions and affine composition, . The first is immediate ( because ); the other two are the second guided exercise. Together they provide what the barrier method needs: a polyhedron barrier, , sums affine compositions of , and is self-concordant for all . Likewise for QP (convex quadratic ) and, as shown later, SOCP and SDP barriers.
Newton on self-concordant functions
The proof (Boyd and Vandenberghe, section 9.6.4) uses two facts: the Dikin ellipsoid lies inside the domain, and there the Hessian varies by at most factor , with distance in the Hessian norm. Compare lesson 13: there depended on , and conditioning; here it is a universal constant depending only on backtracking parameters. Iteration count depends only on how far the objective must fall.
Constants are pessimistic. With and , : the bound guarantees a decrease per damped iteration. In practice each barrier centering takes 5–15 iterations.
Barrier-method complexity
To bound the whole method we must know the decrease needed at each centering.
Proof
Let be the central path’s dual point. By definition of ,
using . Adding on both sides, the right contains (equalities cancel the term). This leaves .
∎Newton’s theorem bounds each stage by iterations. Choose . Since , the numerator is : each stage costs a constant number of Newton steps. Since for , stages number at most . In total,
with universal constants. Each Newton step for a dense LP costs operations (form and factor by Cholesky), so the method is polynomial (in standard asymptotic notation). Express precision in input bits, , to recover Renegar’s bound.
Two qualifications. First, the bound requires extremely short centering stages, which nobody uses; theory guarantees and practice (previous figure) supplies speed with between 10 and 100 and total almost size-independent. Second, is the square root of the barrier parameter, for linear inequalities; generally the bound is . Nesterov and Nemirovskii proved every closed convex set with interior has a self-concordant barrier (the universal barrier) with parameter , extending the scheme theoretically to any convex problem. Practice is restricted to cones with closed-form barriers.
The primal-dual method
The barrier method has nested loops and moves only the primal; the dual emerges after each centering. Modern solvers act more directly: treat perturbed KKT as simultaneous nonlinear equations in , take one Newton step and update every iteration.
Write this for an LP in standard form, as Wright and Nocedal–Wright do:
with . The gap is , and complementary slackness is . The central path solves
for (the earlier ). With , and duality measure (average gap per coordinate; in this section means that, not barrier factor), choose target with centering parameter .
Three observations turn this definition into an efficient, understandable algorithm.
The system reduces to a symmetric positive definite one. Eliminate and from the third row to obtain the normal equation
an positive definite matrix factored by Cholesky. If is sparse, always has the same zero pattern (only changes), so a fill-reducing ordering is computed once and reused (enabling LPs with millions of variables using sparse matrix formats). Final ill-conditioning, with entries and , is benign because of error structure, a nontrivial fact studied by Wright.
Linear residuals fall exactly by factor . Since , the new residual is , and likewise . Thus the method can start outside the feasible set: with and , without phase I. Feasibility arrives gradually, completely as soon as a full step is taken.
allocates the step between centering and progress. With aim directly at KKT (the affine, or affine-scaling direction): most ambitious, but some products reach zero much earlier than others, the boundary step becomes tiny and the method stalls. With aim at the central-path point with the same : center without progress. Short-step path-following methods with have iterations, the same as the barrier method, and are just as slow in practice.
Mehrotra’s predictor-corrector
Which ? Mehrotra (1992) proposed choosing each iteration with cheap information. First calculate affine direction () and admissible step ; estimate resulting gap , and set
If the affine direction progresses far, is tiny and exploits it; if it stalls, approaches 1 and centers. It also adds second-order term to complementarity’s right side: linearizing ignores , estimated by the predictor. This costs one extra substitution using the same Cholesky factorization, the expensive part. Polynomial complexity is not guaranteed (without safeguards examples take tiny steps or fail to converge), but in practice it saves many iterations (about a third versus fixed in the code cell), so nearly all LP codes use it with safeguards.
Barriers for cones: SOCP and SDP
Everything above generalizes to conic problems, with and , given a barrier for cone . The certificate works through logarithmic homogeneity: . is a generalized logarithm of degree for is concave, closed, twice differentiable with negative definite Hessian, has domain the interior of , and satisfies for . Lesson 4’s three cones:
| Cone | Barrier | Degree | Gradient of |
|---|---|---|---|
| Orthant | |||
| Second order | |||
| Semidefinite |
For conic constraints of degrees , the central path gives a dual point with gap : total degree replaces . An SDP with has degree despite scalar variables. All three barriers are self-concordant. For , restrict to a line: , where are eigenvalues of , a sum of of affine functions of .
For semidefinite problems Newton must apply Hessian , and primal-dual methods must linearize while preserving symmetry. The canonical choice is Nesterov–Todd scaling, treating primal and dual symmetrically and available for all symmetric cones (orthant, second order, semidefinite and products). Exponential and power cones are not symmetric and need special techniques; Clarabel and MOSEK include both, ECOS the exponential cone.
Inside a modern solver
A production conic interior-point solver such as Clarabel (Goulart and Chen, 2024), ECOS or MOSEK combines these pieces with numerical engineering (HiGHS’s LP IPM uses a different design, with preconditioned iterative system solves and crossover):
- Preprocessing. Remove redundant rows, fixed variables and dominated constraints; rescale data to balance norms.
- Homogeneous embedding (self-dual in ECOS and MOSEK). Instead of phase I, solve an expanded problem with two more scalars and , always trivially feasible, whose limit yields either a solution or a primal or dual infeasibility certificate (a proving direction). This permits guaranteed output status
infeasible. - Sparse KKT system. Rather than normal equations, densified by even one dense column of , Clarabel and ECOS factor the full KKT system, symmetric indefinite but quasidefinite after small regularization, using sparse (Clarabel uses QDLDL) and approximate minimum-degree ordering. Iterative refinement then recovers accuracy lost to regularization.
- Mehrotra predictor-corrector with Nesterov–Todd scaling and boundary step .
- Relative-tolerance stopping on primal residual, dual residual and gap, typically around .
Each iteration costs a sparse factorization, and iteration count (10–50) depends little on size. This makes interior point predictable: total time grows like factorization cost times nearly constant iteration count, without simplex’s possible combinatorial explosions.
Implementation from scratch
Begin with barrier method plus phase I for an inequality-form LP, with . Function centrar accepts any convex objective returning value, gradient and Hessian, so it also serves phase I and a QP. The random LP is constructed so is not feasible but the dual is ( with ), ensuring boundedness.
import numpy as np
from scipy.linalg import cho_factor, cho_solve
from scipy.optimize import linprog
def centrar(f0, A, b, t, x, tol=1e-6, alfa=0.01, beta=0.5, max_iter=60, parar=None):
"""Newton amortiguado para t*f0(x) - sum(log(b - A x)); devuelve (x, iteraciones)."""
F = lambda z: t * f0(z)[0] - np.sum(np.log(b - A @ z))
for k in range(max_iter):
s = b - A @ x
_, g0, H0 = f0(x)
g = t * g0 + A.T @ (1 / s)
H = t * H0 + A.T @ ((1 / s**2)[:, None] * A)
dx = -cho_solve(cho_factor(H), g)
lam2 = -g @ dx # decremento de Newton al cuadrado
if lam2 / 2 <= tol:
return x, k
Adx = A @ dx # paso máximo dentro del dominio, en cerrado
sale = Adx > 0
paso = min(1.0, 0.99 * np.min(s[sale] / Adx[sale])) if np.any(sale) else 1.0
Fx = F(x) # solo ahora se evalúa F: el paso es factible
while F(x + paso * dx) > Fx - alfa * paso * lam2 and paso > 1e-12:
paso *= beta
x = x + paso * dx
if parar is not None and parar(x):
return x, k + 1
return x, max_iter
def metodo_barrera(f0, A, b, x0, t0=1.0, mu=20.0, eps=1e-6):
m = len(b)
if np.any(A @ x0 >= b):
raise ValueError("x0 debe ser estrictamente factible")
x, t, etapas = x0.copy(), t0, []
while True:
x, k = centrar(f0, A, b, t, x)
etapas.append(k)
if m / t <= eps:
return x, t, etapas
t *= mu
def fase_uno(A, b, x0):
"""min s s.a. A x - s <= b; para en cuanto s < 0."""
m, n = A.shape
s0 = np.max(A @ x0 - b) + 1.0
Ae = np.hstack([A, -np.ones((m, 1))])
f0 = lambda z: (z[-1], np.r_[np.zeros(n), 1.0], np.zeros((n + 1, n + 1)))
z, t, total = np.r_[x0, s0], 1.0, 0
while z[-1] >= 0:
z, k = centrar(f0, Ae, b, t, z, parar=lambda w: w[-1] < 0)
total += k
t *= 20
return z[:n], total
def lp_aleatorio(m, n, semilla=0):
rng = np.random.default_rng(semilla)
A = rng.normal(size=(m, n))
b = A @ rng.normal(size=n) + rng.uniform(0.5, 1.5, size=m)
c = -A.T @ rng.uniform(0.1, 1.0, size=m) # dual factible: el LP está acotado
return A, b, c
m, n = 100, 50
A, b, c = lp_aleatorio(m, n)
lineal = lambda x: (c @ x, c, np.zeros((n, n)))
x0 = np.zeros(n)
print(f"x = 0 viola alguna restricción en {np.max(A @ x0 - b):.2f}")
xf, it1 = fase_uno(A, b, x0)
print(f"fase I: {it1} pasos de Newton, holgura mínima {np.min(b - A @ xf):.3f}")
x, t, etapas = metodo_barrera(lineal, A, b, xf, t0=1.0, mu=20.0, eps=1e-6)
print("pasos de Newton por centrado:", etapas, " total:", sum(etapas))
ref = linprog(c, A_ub=A, b_ub=b, bounds=(None, None), method="highs")
print(f"HiGHS: {ref.fun:.10f} barrera: {c @ x:.10f} diferencia: {c @ x - ref.fun:.1e} m/t = {m / t:.1e}")
# en cada punto del camino central, lam_i = 1/(t s_i) es dual factible y g(lam) = -b^T lam
print("\n t subóptimo gap c^T x - g(lam) m/t |A^T lam + c| t*subóptimo")
for tt in [1.0, 10.0, 100.0, 1000.0, 1e4]:
xx, _ = centrar(lineal, A, b, tt, xf, tol=1e-10, max_iter=200)
lam = 1 / (tt * (b - A @ xx))
sub = c @ xx - ref.fun
print(f"{tt:6.0f} {sub:.4e} {c @ xx + b @ lam:.6e} {m / tt:.0e} {np.linalg.norm(A.T @ lam + c):.1e} {tt * sub:6.2f}")Check several things in the output. Phase I finds an interior point in about twenty Newton steps without solving to completion. Centerings take 6–12 steps, about 70 total for a LP. The solution matches HiGHS within . In the table, dual point is feasible up to at most residual (from inexact centering, stopping at ) and its gap equals to six digits. The final column confirms the central-path figure: times suboptimality remains around , half of .
The same code solves a QP: only f0 changes. For bounded least squares, with , SciPy provides an exact reference, lsq_linear.
import numpy as np
from scipy.optimize import lsq_linear
rng = np.random.default_rng(1)
F = rng.normal(size=(80, 30))
g = F @ rng.uniform(-0.5, 1.5, size=30) + 0.1 * rng.normal(size=80)
P, q = F.T @ F, -F.T @ g
cuadratica = lambda x: (0.5 * x @ P @ x + q @ x, P @ x + q, P)
Ac = np.vstack([np.eye(30), -np.eye(30)]) # x <= 1 y -x <= 0
bc = np.r_[np.ones(30), np.zeros(30)]
xq, tq, etapas_q = metodo_barrera(cuadratica, Ac, bc, np.full(30, 0.5), mu=20.0, eps=1e-7)
ref = lsq_linear(F, g, bounds=(0, 1), tol=1e-12)
f = lambda x: 0.5 * np.sum((F @ x - g) ** 2)
print("pasos de Newton por centrado:", etapas_q)
print(f"barrera: {f(xq):.10f} lsq_linear: {f(ref.x):.10f} diferencia: {f(xq) - f(ref.x):.1e} m/t = {60 / tq:.1e}")
print("cotas activas en la solución:", int(np.sum(ref.x < 1e-6)), "en 0 y", int(np.sum(ref.x > 1 - 1e-6)), "en 1")Now self-concordance’s promise in two experiments. First rescale each variable by factors from to : centering is the same problem in different coordinates, the Hessian’s solution condition number explodes, and Newton does not notice. Gradient descent with the same backtracking does. Second, measure total Newton steps of the full barrier method as grows.
import numpy as np
def descenso_gradiente(t, c, A, b, x, tol=1e-6, max_iter=400):
F = lambda z: t * c @ z - np.sum(np.log(b - A @ z))
for k in range(max_iter):
s = b - A @ x
g = t * c + A.T @ (1 / s)
H = A.T @ ((1 / s**2)[:, None] * A)
if g @ np.linalg.solve(H, g) / 2 <= tol: # mismo criterio que Newton
return x, k
p = 1.0
while np.any(b - A @ (x - p * g) <= 0):
p *= 0.5
while F(x - p * g) > F(x) - 0.01 * p * (g @ g):
p *= 0.5
x = x - p * g
return x, max_iter
m, n = 60, 10
A, b, c = lp_aleatorio(m, n, semilla=3)
xf, _ = fase_uno(A, b, np.zeros(n))
print("escala Newton cond(hessiano en x*) gradiente")
for k in [0, 1, 2, 3]:
D = np.diag(10.0 ** np.linspace(-k, k, n)) # x = D x': mismas soluciones, otras coordenadas
AD, cD, x0 = A @ D, D @ c, np.linalg.solve(D, xf)
lineal_D = lambda z: (cD @ z, cD, np.zeros((n, n)))
xs, it_newton = centrar(lineal_D, AD, b, 10.0, x0)
s = b - AD @ xs
cond = np.linalg.cond(AD.T @ ((1 / s**2)[:, None] * AD))
it_gd = descenso_gradiente(10.0, cD, AD, b, x0)[1] if k <= 1 else "-"
print(f"10^±{k} {it_newton:3d} {cond:9.1e} {it_gd}")
print("\n m n centrados Newton total")
for m in [25, 50, 100, 200, 400]:
n = m // 4
A, b, c = lp_aleatorio(m, n, semilla=1)
xf, _ = fase_uno(A, b, np.zeros(n))
_, _, etapas = metodo_barrera(lambda z: (c @ z, c, np.zeros((n, n))), A, b, xf, mu=20.0, eps=1e-6)
print(f"{m:4d} {n:4d} {len(etapas):6d} {sum(etapas):6d}")Condition number rises from to and Newton takes exactly the same steps (the same algorithm in different coordinates); gradient descent fails to converge in 400 iterations under rescaling. Multiplying by 16 barely changes total Newton steps: one extra stage (starting higher) and a few iterations per stage.
Finally, primal-dual with Mehrotra predictor-corrector for a standard-form LP with data ensuring primal and dual strict feasibility. Start , is infeasible, and phase I is unnecessary.
import time
import numpy as np
from scipy.linalg import cho_factor, cho_solve
from scipy.optimize import linprog
def lp_estandar(m, n, semilla=0):
rng = np.random.default_rng(semilla)
A = rng.normal(size=(m, n))
b = A @ rng.uniform(0.5, 1.5, size=n) # x > 0 factible
c = A.T @ rng.normal(size=m) + rng.uniform(0.5, 1.5, size=n) # s > 0 factible en el dual
return A, b, c
def paso_frontera(v, dv):
neg = dv < 0
return min(1.0, np.min(-v[neg] / dv[neg])) if np.any(neg) else 1.0
def punto_interior(A, b, c, mehrotra=True, sigma=0.1, tol=1e-8, eta=0.99, max_iter=100):
m, n = A.shape
x, y, s = np.ones(n), np.zeros(m), np.ones(n)
nb, nc = 1 + np.linalg.norm(b), 1 + np.linalg.norm(c)
for k in range(max_iter):
rp, rd, mu = A @ x - b, A.T @ y + s - c, x @ s / n
if np.linalg.norm(rp) / nb < tol and np.linalg.norm(rd) / nc < tol and mu < tol:
return x, y, s, k
d = x / s
fac = cho_factor(A @ (d[:, None] * A.T)) # la única factorización de la iteración
def direccion(rc):
dy = cho_solve(fac, -rp - A @ (d * rd) - A @ (rc / s))
ds = -rd - A.T @ dy
return (rc - x * ds) / s, dy, ds
if mehrotra:
dxa, _, dsa = direccion(-x * s) # predictor: sigma = 0
aa = min(paso_frontera(x, dxa), paso_frontera(s, dsa))
sig = ((x + aa * dxa) @ (s + aa * dsa) / n / mu) ** 3
dx, dy, ds = direccion(-x * s - dxa * dsa + sig * mu) # corrector
else:
dx, dy, ds = direccion(-x * s + sigma * mu)
a = min(1.0, eta * min(paso_frontera(x, dx), paso_frontera(s, ds)))
x, y, s = x + a * dx, y + a * dy, s + a * ds
return x, y, s, max_iter
A, b, c = lp_estandar(30, 60)
x, y, s, k = punto_interior(A, b, c)
ref = linprog(c, A_eq=A, b_eq=b, bounds=(0, None), method="highs")
print(f"{k} iteraciones primal {c @ x:.8f} dual {b @ y:.8f} HiGHS {ref.fun:.8f}")
print("\n n m Mehrotra sigma=0.1 tiempo error relativo")
for n in [25, 50, 100, 200, 400]:
A, b, c = lp_estandar(n // 2, n, semilla=n)
t0 = time.perf_counter()
x, y, s, k = punto_interior(A, b, c)
dt = time.perf_counter() - t0
k01 = punto_interior(A, b, c, mehrotra=False, sigma=0.1)[3]
ref = linprog(c, A_eq=A, b_eq=b, bounds=(0, None), method="highs")
print(f"{n:4d} {n // 2:4d} {k:6d} {k01:6d} {dt:.3f}s {abs(c @ x - ref.fun) / abs(ref.fun):.1e}")About thirty lines of method, and iteration count barely changes while grows 16-fold: the motivation’s “twenty-row table”. Cost per iteration, however, grows like forming and factoring , dense here: . Mehrotra saves about one third of iterations versus fixed , with one factorization per iteration in both cases.
The professional version
In Python, scipy.optimize.linprog calls HiGHS. method="highs" lets HiGHS choose; "highs-ds" forces dual simplex and "highs-ipm" interior point (with vertex crossover). Before trusting the result, inspect how it finished: status, message and tolerances.
import time
import numpy as np
from scipy.optimize import linprog
A, b, c = lp_aleatorio(400, 150, semilla=5)
for metodo in ["highs-ds", "highs-ipm"]:
t0 = time.perf_counter()
r = linprog(c, A_ub=A, b_ub=b, bounds=(None, None), method=metodo,
options={"primal_feasibility_tolerance": 1e-9, "dual_feasibility_tolerance": 1e-9})
dt = time.perf_counter() - t0
viol = max(0.0, np.max(A @ r.x - b))
lam = -r.ineqlin.marginals # multiplicadores >= 0 de A x <= b
print(f"{metodo:10s} estado {r.status} ({r.message.split('(')[0].strip()}) iteraciones {r.nit} {dt:.3f}s")
print(f" objetivo {r.fun:.10f} violación primal {viol:.1e} "
f"residuo dual {np.linalg.norm(A.T @ lam + c):.1e} gap {c @ r.x + b @ lam:.1e}")Both calls give the same optimum, but verify rather than assume: primal violation, multiplier-reconstructed dual residual and gap are the three quantities an IPM drives to zero. CVXPY provides a higher-level interface and selectable solver; in current versions Clarabel is the default for many conic problems:
import cvxpy as cp
x = cp.Variable(n)
prob = cp.Problem(cp.Minimize(c @ x), [A @ x <= b])
prob.solve(solver=cp.CLARABEL, verbose=True) # imprime una fila por iteración
print(prob.status, prob.value)
print(prob.solver_stats.num_iters, prob.solver_stats.solve_time)
lam = prob.constraints[0].dual_value # multiplicadores de A x <= b
Clarabel’s log has one row per iteration with primal and dual cost, gap, primal and dual residuals, homogeneous-embedding ratio , and step length. You now know each column’s meaning.
Common mistakes
Exercises
More than one answer may be correct.
Step 1 of 4. Which dual point do you construct?
Step 1 of 4. How do you check is self-concordant?
newton_centering(t, c, A, b, x0) to minimize using damped Newton and return the minimizer. Requirements: raise ValueError if x0 is not strictly feasible; in backtracking, shrink the step until b - A @ (x + paso*dx) > 0 before evaluating objective and Armijo (tests replace np.log with a version raising an error on nonpositive arguments, so out-of-domain evaluation fails); stop when tol. Starter code is naive: it works until the full step crosses a constraint.import numpy as np
def newton_centering(t, c, A, b, x0, tol=1e-9, alpha=0.01, beta=0.5, max_iter=100):
"""Minimiza t c^T x - sum(log(b - A x)) desde x0 estrictamente factible. Devuelve x."""
A, b, c = np.asarray(A, dtype=float), np.asarray(b, dtype=float), np.asarray(c, dtype=float)
x = np.asarray(x0, dtype=float).copy()
f = lambda z: t * c @ z - np.sum(np.log(b - A @ z))
for _ in range(max_iter):
s = b - A @ x
g = t * c + A.T @ (1 / s)
H = A.T @ ((1 / s**2)[:, None] * A)
dx = -np.linalg.solve(H, g)
lam2 = -g @ dx
if lam2 / 2 <= tol:
break
paso = 1.0
# tu código: antes de Armijo, el paso debe dejar b - A(x + paso dx) > 0
while f(x + paso * dx) > f(x) - alpha * paso * lam2:
paso *= beta
x = x + paso * dx
return xSummary
- Barrier is convex, smooth and diverges at the boundary; minimizing better approximates the constrained problem as grows.
- Central path solves KKT with perturbed complementary slackness . Its dual point gives gap ; in a nondegenerate LP actual suboptimality is .
- The barrier method centers with damped Newton (backtracking respects the domain before Armijo), multiplies by and stops when . It needs phase I or a strictly feasible start. In practice, between 10 and 100 and a few dozen Newton steps total.
- Self-concordance, , is affine invariant, preserved by sums and affine composition and gives a Newton iteration bound with universal constants. The barrier method then needs Newton steps.
- Primal-dual takes one Newton step per iteration on perturbed KKT, starts infeasibly (linear residuals fall by ), controls centering with and, with Mehrotra predictor-corrector, solves LPs in 10–50 iterations almost independently of size.
- Generalized logarithms (, ) similarly solve SOCP and SDP with gap . Modern conic solvers (Clarabel, ECOS, MOSEK) add homogeneous embedding, sparse factorization and relative tolerances worth checking.