TExcelTAD
Home › SciPy › SciPy Linear Programming

SciPy Linear Programming

Linear programming (LP) optimizes a linear objective — profit, cost, time — subject to linear constraints. It looks restrictive, but a huge number of planning problems fit: production mixes, diets, shipping, staff schedules. Because everything is linear, LP solvers are fast and always find the true global optimum.

SciPy solves LP problems with scipy.optimize.linprog(), which uses the high-performance HiGHS solvers. Its standard form is:

text
minimize     c @ x
subject to   A_ub @ x <= b_ub      (inequalities)
             A_eq @ x == b_eq      (equalities)
             lower <= x <= upper   (bounds, default 0 <= x)

A production problem

A workshop makes chairs (profit 30) and tables (profit 50). A chair needs 2 h of carpentry and 1 h of finishing; a table needs 3 h of carpentry and 3 h of finishing. Each week there are 120 h of carpentry and 90 h of finishing. How many of each maximize profit?

linprog minimizes, so we minimize the negative profit:

python · try it yourself
from scipy.optimize import linprog

c = [-30, -50]                 # maximize 30*chairs + 50*tables
A_ub = [[2, 3],                # carpentry hours
        [1, 3]]                # finishing hours
b_ub = [120, 90]

res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=[(0, None), (0, None)])
chairs, tables = res.x
print(res.message)
print(f"chairs = {chairs:.1f}, tables = {tables:.1f}")
print(f"profit = {-res.fun:.1f}")
print("hours left (slack):", res.slack)
Optimization terminated successfully. (HiGHS Status 7: Optimal)
chairs = 30.0, tables = 20.0
profit = 1900.0
hours left (slack): [0. 0.]

Both resources are used completely (slack 0), so neither could be spared without lowering profit.

Shadow prices

How much would one extra hour of each resource be worth? The solver reports this as the marginals (dual values) of the constraints. For a minimization of negative profit they are negative, so flip the sign:

python · try it yourself
from scipy.optimize import linprog

res = linprog([-30, -50], A_ub=[[2, 3], [1, 3]], b_ub=[120, 90])
carpentry, finishing = -res.ineqlin.marginals
print(f"one more carpentry hour adds {carpentry:.2f} profit")
print(f"one more finishing hour adds {finishing:.2f} profit")

check = linprog([-30, -50], A_ub=[[2, 3], [1, 3]], b_ub=[121, 90])
print(f"re-solved with 121 carpentry hours: {-check.fun:.2f} (was {-res.fun:.2f})")
one more carpentry hour adds 13.33 profit
one more finishing hour adds 3.33 profit
re-solved with 121 carpentry hours: 1913.33 (was 1900.00)

A diet problem with equality constraints

Choose amounts (in 100 g units) of three foods to meet nutrition targets at minimum cost. "At least" constraints become <= constraints by multiplying both sides by −1:

python · try it yourself
import numpy as np
from scipy.optimize import linprog

foods = ["oats", "milk", "beans"]
cost = np.array([0.30, 0.25, 0.40])           # per 100 g
protein = np.array([13, 3.4, 21])             # g per 100 g
fibre = np.array([10, 0, 15])                 # g per 100 g
calcium = np.array([50, 120, 140])            # mg per 100 g
calories = np.array([380, 65, 330])           # kcal per 100 g

A_ub = -np.vstack([protein, fibre, calcium])  # protein >= 60, fibre >= 30, calcium >= 1000
b_ub = -np.array([60, 30, 1000])
A_eq = [calories]                             # calories == 2000
b_eq = [2000]

res = linprog(cost, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
              bounds=[(0, 4)] * 3)           # at most 400 g of each
for name, amount in zip(foods, res.x):
    print(f"{name:5}: {amount * 100:6.1f} g")
print(f"daily cost: {res.fun:.2f}")
print(f"protein {protein @ res.x:.1f} g, fibre {fibre @ res.x:.1f} g, "
      f"calcium {calcium @ res.x:.0f} mg, calories {calories @ res.x:.0f}")
oats :  125.1 g
milk :  314.5 g
beans:  400.0 g
daily cost: 2.76
protein 111.0 g, fibre 72.5 g, calcium 1000 mg, calories 2000

Integer solutions

You can't build 20.33 tables. When variables must be whole numbers, pass integrality= (1 = integer) to linprog, or use milp(), SciPy's mixed-integer solver:

python · try it yourself
import numpy as np
from scipy.optimize import milp, LinearConstraint, Bounds

c = np.array([-30, -50])
# With 121 carpentry and 91 finishing hours the LP optimum is 30 chairs and 20.33 tables
constraint = LinearConstraint([[2, 3], [1, 3]], ub=[121, 91])
res = milp(c, constraints=constraint, integrality=[1, 1], bounds=Bounds(0, np.inf))
print("status :", res.message)
print("chairs, tables:", res.x.astype(int))
print("profit :", -res.fun)
status : Optimization terminated successfully. (HiGHS Status 7: Optimal)
chairs, tables: [32 19]
profit : 1910.0

When things go wrong

res.status tells you how the solve ended. The two common failures are an infeasible problem (no point satisfies every constraint) and an unbounded one (the objective can improve forever):

python · try it yourself
from scipy.optimize import linprog

# x >= 5 and x <= 3 can't both hold
infeasible = linprog([1], A_ub=[[-1], [1]], b_ub=[-5, 3])
print(infeasible.status, "-", infeasible.message)

# maximize x with no upper limit
unbounded = linprog([-1], bounds=[(0, None)])
print(unbounded.status, "-", unbounded.message)
2 - The problem is infeasible. (HiGHS Status 8: model_status is Infeasible; primal_status is At lower/fixed bound)
3 - The problem is unbounded. (HiGHS Status 10: model_status is Unbounded; primal_status is At upper bound)
status Meaning
0 Optimal solution found
1 Iteration or time limit reached
2 Problem is infeasible
3 Problem is unbounded
4 Numerical difficulties

Test yourself

linprog only minimizes. How do you maximize profit 30x + 50y?

  1. Pass maximize=True
  2. Minimize -30x - 50y
  3. Use bounds=(None, 0)
  4. Use A_eq instead of A_ub

How do you write the constraint 'protein ≥ 60' for linprog's A_ub/b_ub?

  1. protein @ x <= 60
  2. -protein @ x <= -60
  3. protein @ x == 60
  4. It can't be expressed

What does a constraint's marginal (shadow price) tell you?

  1. How many iterations were needed
  2. How much the objective changes per extra unit of that resource
  3. Whether the problem is infeasible
  4. The slack of the constraint