Linear Programs
A linear program (LP) has a linear objective and linear constraints. LPs model blending, production planning, transportation, network flows, scheduling relaxations and much more, and they can be solved reliably with millions of variables. They are the backbone of operations research and the building block of integer programming.
Forms of an LP
The inequality form and the standard form are equivalent:
Conversions:
| From | To standard form |
|---|---|
| , slack | |
| , surplus | |
| free variable | with |
| maximize | minimize |
The simplex method works on the standard form; modelling is usually easier in the inequality form.
A classic: the diet problem
Choose amounts of foods to meet nutrient requirements at minimum cost. With food costs , nutrient contents (nutrient per unit of food ) and requirements : minimize s.t. , .
import numpy as np
from scipy.optimize import linprog
foods = ["oats", "milk", "beans", "rice", "eggs"]
cost = np.array([0.30, 0.50, 0.60, 0.20, 0.90]) # per serving
# oats milk beans rice eggs
A = np.array([[ 5, 8, 9, 3, 12], # protein (g)
[ 2, 0, 6, 1, 0], # fibre (g)
[ 1, 30, 4, 1, 5], # calcium (% daily value)
[150, 120, 230, 200, 140]]) # energy (kcal)
req = np.array([50, 25, 100, 2000])
res = linprog(cost, A_ub=-A, b_ub=-req, bounds=[(0, 10)] * 5, method="highs")
for name, q in zip(foods, res.x):
if q > 1e-9:
print(f"{name:6s} {q:6.3f} servings")
print("cost per day:", round(res.fun, 4))
print("nutrients:", np.round(A @ res.x, 2), "vs required", req)milk 2.729 servings
beans 3.430 servings
rice 4.418 servings
cost per day: 4.3061
nutrients: [ 65.96 25. 100. 2000. ] vs required [ 50 25 100 2000]
Only 3 of the 5 foods appear. That is typical: an optimal basic solution has no more non-zero variables than there are constraints (here 4 nutrient rows; the upper bounds of 10 servings also count when they bind). The Geometry of Linear Programs explains why.
Network flows
Many LPs live on graphs. A minimum-cost flow sends supply from sources to sinks along edges with costs and capacities; flow conservation at each node is an equality constraint with the node-edge incidence matrix :
import numpy as np
from scipy.optimize import linprog
edges = [("S", "A", 2, 4), ("S", "B", 4, 3), ("A", "B", 1, 2), ("A", "T", 5, 3), ("B", "T", 1, 5)] # from, to, cost, capacity
nodes = ["S", "A", "B", "T"]
supply = {"S": 5, "A": 0, "B": 0, "T": -5}
B = np.zeros((4, len(edges)))
for j, (u, v, _, _) in enumerate(edges):
B[nodes.index(u), j] = 1; B[nodes.index(v), j] = -1
res = linprog([e[2] for e in edges], A_eq=B, b_eq=[supply[n] for n in nodes],
bounds=[(0, e[3]) for e in edges], method="highs")
for (u, v, c, cap), f in zip(edges, res.x):
print(f"{u}->{v}: flow {f + 0:.0f} / {cap}")
print("total cost:", round(res.fun, 4))S->A: flow 2 / 4
S->B: flow 3 / 3
A->B: flow 2 / 2
A->T: flow 0 / 3
B->T: flow 5 / 5
total cost: 23.0
Network LPs have a special property: with integer supplies and capacities, the optimal vertex is integral automatically (the incidence matrix is totally unimodular), so shortest paths, assignments and max-flow come out as whole numbers without integer programming.
What LPs cannot model directly
Products of variables, fixed costs ("pay 100 if you produce anything"), either/or choices and integrality all break linearity. Some nonlinear-looking constraints do become linear with a trick (absolute values, maxima, ratios with fixed sign); see Modelling with Linear Programs. The rest need integer programming.
In software
scipy.optimize.linprog(method="highs"); open-source solvers HiGHS, CLP, GLPK; commercial Gurobi, CPLEX, Xpress, MOSEK.- Modelling layers (PuLP, Pyomo, OR-Tools'
pywraplp, JuMP) let you write constraints with named variables instead of building matrices by hand.
Exercises
Exercise 1: Standard form
Convert: minimize s.t. , , , free.
Answer
Minimize s.t. , , all variables .
Solution
Split the free variable, add a slack to the row and subtract a surplus from the row.
Exercise 2: Count non-zeros
An LP in standard form has 3 equality constraints and 10 variables. At most how many variables are non-zero at a basic optimal solution?
Answer
Solution
A basic solution chooses 3 linearly independent columns (the basis) and sets the other 7 variables to zero.
Exercise 3: Change the diet (code)
Forbid rice (upper bound 0) in the diet problem. How much does the daily cost rise?
Answer
From 4.3061 to 4.8903 per day, an increase of about 0.58.
Solution
import numpy as np
from scipy.optimize import linprog
cost = np.array([0.30, 0.50, 0.60, 0.20, 0.90])
A = np.array([[5, 8, 9, 3, 12], [2, 0, 6, 1, 0], [1, 30, 4, 1, 5], [150, 120, 230, 200, 140]])
req = np.array([50, 25, 100, 2000])
base = linprog(cost, A_ub=-A, b_ub=-req, bounds=[(0, 10)] * 5).fun
norice = linprog(cost, A_ub=-A, b_ub=-req, bounds=[(0, 10)] * 3 + [(0, 0), (0, 10)]).fun
print(round(base, 4), round(norice, 4), "increase:", round(norice - base, 4))4.3061 4.8903 increase: 0.5841
Going further: Linear Programming & Duality for Algorithms in the Algorithm Theory track uses LPs for combinatorial problems: total unimodularity, integrality gaps and LP-based approximation.
Test yourself
In standard form, an inequality becomes…
- with
- with
- it cannot be converted
Why do min-cost network flow LPs give integer flows for integer data?
- Solvers round the answer
- The incidence matrix is totally unimodular, so vertices are integral
- Flows are always 0 or 1
- LPs only have integer solutions
Which constraint is NOT linear?