Modelling with Linear Programs
Many problems that do not look linear can be written as LPs with a few standard tricks. Knowing them lets you use fast, reliable LP solvers for robust regression, worst-case planning, ratio objectives and more. Each trick adds variables or constraints so that the nonlinear part disappears.
Trick 1: absolute values
Minimize with affine in : introduce with and minimize . At the optimum . This gives least absolute deviations (L1) regression, which resists outliers:
import numpy as np
from scipy.optimize import linprog
rng = np.random.default_rng(0)
x = np.linspace(0, 10, 30); y = 2 * x + 1 + rng.normal(scale=0.5, size=30)
y[[5, 20]] += [25, -30] # two gross outliers
X = np.column_stack([np.ones_like(x), x]); n = len(x)
# variables: (w0, w1, t_1..t_n); minimize sum t s.t. X w - y <= t, -(X w - y) <= t
c = np.r_[0, 0, np.ones(n)]
A_ub = np.block([[X, -np.eye(n)], [-X, -np.eye(n)]]); b_ub = np.r_[y, -y]
res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=[(None, None)] * 2 + [(0, None)] * n, method="highs")
w_l1 = res.x[:2]
w_l2 = np.linalg.lstsq(X, y, rcond=None)[0]
print("true line: intercept 1, slope 2")
print("L1 (LP) fit: ", np.round(w_l1, 3))
print("least squares:", np.round(w_l2, 3))true line: intercept 1, slope 2
L1 (LP) fit: [0.994 1.977]
least squares: [3.393 1.476]
Trick 2: minimax (the epigraph trick)
Minimize : introduce , require for all , minimize . This gives Chebyshev (L-infinity) fitting, minimizing the worst error:
import numpy as np
from scipy.optimize import linprog
# best polynomial of degree 3 approximating e^x on [0, 1] in the max-error sense
xs = np.linspace(0, 1, 201); ys = np.exp(xs)
V = np.vander(xs, 4, increasing=True); n = 4
c = np.r_[np.zeros(n), 1.0] # minimize t
A_ub = np.block([[V, -np.ones((len(xs), 1))], [-V, -np.ones((len(xs), 1))]])
res = linprog(c, A_ub=A_ub, b_ub=np.r_[ys, -ys], bounds=[(None, None)] * n + [(0, None)], method="highs")
coef = res.x[:n]
ls = np.linalg.lstsq(V, ys, rcond=None)[0]
print("minimax max error: ", f"{res.x[-1]:.2e}")
print("least-squares max error:", f"{np.abs(V @ ls - ys).max():.2e}")minimax max error: 5.45e-04
least-squares max error: 1.02e-03
Trick 3: piecewise-linear convex costs
A convex piecewise-linear cost (volume discounts reversed, overtime pay, tax brackets) is modelled exactly like the minimax trick: a variable for every piece. Concave pieces (real volume discounts) need integer variables.
Trick 4: linear-fractional objectives
Minimize over a polyhedron with a positive denominator. The Charnes-Cooper transformation , turns it into an LP in . Used for cost per unit, return per risk-unit and efficiency (DEA) problems.
Trick 5: goal programming and soft constraints
Turn a hard constraint into a soft one by adding a violation variable : , and charge in the objective. The model stays feasible and reports how much each target is missed.
import numpy as np
from scipy.optimize import linprog
# Staffing: need >= [6, 9, 7] workers in 3 shifts but only 20 people in total.
# Each person works one shift. Shortfalls cost 10 per missing person in shift 1-2 and 4 in shift 3.
need = np.array([6, 9, 7]); penalty = np.array([10, 10, 4])
# variables: workers w1..w3, shortfalls v1..v3
c = np.r_[np.zeros(3), penalty]
A_ub = np.vstack([np.r_[np.ones(3), np.zeros(3)], # total staff <= 20
np.hstack([-np.eye(3), -np.eye(3)])]) # w_i + v_i >= need_i
res = linprog(c, A_ub=A_ub, b_ub=np.r_[20, -need], bounds=[(0, None)] * 6, method="highs")
print("staff per shift:", np.round(res.x[:3], 4) + 0, " shortfall:", np.round(res.x[3:], 4) + 0)staff per shift: [6. 9. 5.] shortfall: [0. 0. 2.]
The two missing people are taken from the cheapest shift to under-staff.
In software
- CVXPY applies these reformulations automatically: write
cp.norm1(X @ w - y)orcp.max(...)and it builds the LP. sklearn.linear_model.QuantileRegressorsolves quantile regression (a weighted absolute-value loss) as an LP with HiGHS.
Exercises
Exercise 1: Formulate
Write "minimize " as an LP.
Answer
Minimize s.t. , .
Solution
Every is optimal with value 4: the sum of distances to and 3 is constant between them. An LP solver returns one of those points (a vertex of the reformulated problem).
Exercise 2: Which trick?
You want the production plan that minimizes the largest overtime among 5 factories. Which trick applies?
Answer
Minimax (epigraph): one variable each factory's overtime.
Solution
Minimize subject to for plus the plan's own constraints. If overtime is , it is itself modelled with a variable , .
Exercise 3: Median as an LP (code)
The L1 fit of a constant to data, , is the median. Check with linprog on .
Answer
, the median.
Solution
import numpy as np
from scipy.optimize import linprog
y = np.array([1.0, 2.0, 4.0, 7.0, 20.0]); n = len(y)
A = np.block([[np.ones((n, 1)), -np.eye(n)], [-np.ones((n, 1)), -np.eye(n)]])
r = linprog(np.r_[0, np.ones(n)], A_ub=A, b_ub=np.r_[y, -y], bounds=[(None, None)] + [(0, None)] * n, method="highs")
print(round(r.x[0], 4), np.median(y))4.0 4.0
Test yourself
To minimize with an LP you…
- square the residuals
- add with and minimize
- use integer variables
- cannot
Minimizing the maximum of several affine functions becomes an LP by…
- the epigraph trick: minimize with each function
- taking logarithms
- averaging them
- branch and bound
Compared with least squares, L1 regression is…
- more sensitive to outliers
- less sensitive to outliers
- the same
- only for integers