TExcelTAD
Home › Optimization › Modelling with Linear Programs

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 ∑i∣ri∣\sum_i\lvert r_i \rvert with rir_i affine in x\mathbf{x}: introduce tit_i with −ti≤ri≤ti-t_i \le r_i \le t_i and minimize ∑iti\sum_it_i. At the optimum ti=∣ri∣t_i = \lvert r_i \rvert. This gives least absolute deviations (L1) regression, which resists outliers:

python · try it yourself
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 max⁡i(aiTx+bi)\max_i(\mathbf{a}_i^T\mathbf{x} + b_i): introduce tt, require aiTx+bi≤t\mathbf{a}_i^T\mathbf{x} + b_i \le t for all ii, minimize tt. This gives Chebyshev (L-infinity) fitting, minimizing the worst error:

python · try it yourself
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 f(x)=max⁡k(akx+bk)f(x) = \max_k(a_kx + b_k) (volume discounts reversed, overtime pay, tax brackets) is modelled exactly like the minimax trick: a variable t≥akx+bkt \ge a_kx + b_k for every piece. Concave pieces (real volume discounts) need integer variables.

Trick 4: linear-fractional objectives

Minimize cTx+deTx+f\frac{\mathbf{c}^T\mathbf{x} + d}{\mathbf{e}^T\mathbf{x} + f} over a polyhedron with a positive denominator. The Charnes-Cooper transformation y=x/(eTx+f)\mathbf{y} = \mathbf{x}/(\mathbf{e}^T\mathbf{x} + f), z=1/(eTx+f)z = 1/(\mathbf{e}^T\mathbf{x} + f) turns it into an LP in (y,z)(\mathbf{y}, z). Used for cost per unit, return per risk-unit and efficiency (DEA) problems.

Trick 5: goal programming and soft constraints

Turn a hard constraint aTx≤b\mathbf{a}^T\mathbf{x} \le b into a soft one by adding a violation variable v≥0v \ge 0: aTx≤b+v\mathbf{a}^T\mathbf{x} \le b + v, and charge ρv\rho v in the objective. The model stays feasible and reports how much each target is missed.

python · try it yourself
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) or cp.max(...) and it builds the LP.
  • sklearn.linear_model.QuantileRegressor solves quantile regression (a weighted absolute-value loss) as an LP with HiGHS.

Exercises

Exercise 1: Formulate

Write "minimize ∣x−3∣+∣x+1∣\lvert x - 3 \rvert + \lvert x + 1 \rvert" as an LP.

Answer

Minimize t1+t2t_1 + t_2 s.t. −t1≤x−3≤t1-t_1 \le x - 3 \le t_1, −t2≤x+1≤t2-t_2 \le x + 1 \le t_2.

Solution

Every x∈[−1,3]x \in [-1, 3] is optimal with value 4: the sum of distances to −1-1 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 t≥t \ge each factory's overtime.

Solution

Minimize tt subject to overtimek(x)≤t\text{overtime}_k(\mathbf{x}) \le t for k=1,…,5k = 1, \dots, 5 plus the plan's own constraints. If overtime is max⁡(0,hours−capacity)\max(0, \text{hours} - \text{capacity}), it is itself modelled with a variable ok≥0o_k \ge 0, ok≥hoursk−capko_k \ge \text{hours}_k - \text{cap}_k.

Exercise 3: Median as an LP (code)

The L1 fit of a constant to data, min⁡c∑i∣yi−c∣\min_c\sum_i\lvert y_i - c \rvert, is the median. Check with linprog on y=(1,2,4,7,20)\mathbf{y} = (1, 2, 4, 7, 20).

Answer

c=4c = 4, the median.

Solution
python · try it yourself
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 ∑i∣ri∣\sum_i\lvert r_i \rvert with an LP you…

  1. square the residuals
  2. add tit_i with −ti≤ri≤ti-t_i \le r_i \le t_i and minimize ∑ti\sum t_i
  3. use integer variables
  4. cannot

Minimizing the maximum of several affine functions becomes an LP by…

  1. the epigraph trick: minimize tt with each function ≤t\le t
  2. taking logarithms
  3. averaging them
  4. branch and bound

Compared with least squares, L1 regression is…

  1. more sensitive to outliers
  2. less sensitive to outliers
  3. the same
  4. only for integers