🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Optimization and Linear Programming for Decision Science

⭐ Premium

Optimization and Linear Programming for Decision Science

Predictive models tell you what is likely to happen; optimization tells you what to do about it. A churn score identifies at-risk customers, but a linear program (LP) decides which customers to contact under a budget and contact-frequency limit to maximize retained revenue. Forecasting gives you next quarter's demand; a mixed-integer program (MIP) decides which SKUs to stock in which warehouses. Linear programming is the workhorse of decision science: fast, interpretable, and supported by solvers that handle millions of variables in seconds.

This lesson builds the formulation skill that matters more than any solver syntax — translating a prose business problem into decision variables, an objective, and constraints — then solves it with SciPy's HiGHS interface and PuLP, reads sensitivity reports that quantify the value of each constraint, and covers the infeasibility and integrality issues that trip up first production models.

What You'll Learn

  • 1Translate a business problem into decision variables, objective, and constraints
  • 2Solve LPs with SciPy linprog and model them declaratively with PuLP
  • 3Interpret dual values and reduced costs to quantify the marginal value of resources
  • 4Diagnose infeasibility and decide when to use integer variables instead of continuous LP

Prerequisites

  • !Linear algebra: matrices, vectors, dot products
  • !Basic Python and pandas
  • !Comfort with inequality constraints and objective functions

Formulation: the skill before the solver

Every LP has the same skeleton. Decision variables are the quantities you control — how much of each product to make, which customers to contact, how much to ship on each route. The objective is a single scalar you maximize or minimize, usually linear in the variables. Constraints restrict the feasible set: budgets, capacities, minimum service levels, logical requirements.

The canonical form is: maximize (or minimize) c^T x subject to A_ub x <= b_ub, A_eq x = b_eq, and bounds on x. Real problems rarely arrive in canonical form; the formulation work is converting a paragraph of business rules into that structure.

Consider a production-planning problem: a factory makes three products on a shared machine with limited weekly hours, using limited raw material, with minimum commitments on two products and nonnegativity on all.

ProductProfit/unitMachine hrs/unitMaterial lbs/unitMin commitment
A402350
B30120
C503420

Available: 200 machine hours, 400 lbs material. Variables: x_A, x_B, x_C >= 0 (units to produce). Objective: max 40*x_A + 30*x_B + 50*x_C. Constraints: 2*x_A + x_B + 3*x_C <= 200 (machine), 3*x_A + 2*x_B + 4*x_C <= 400 (material), x_A >= 50, x_C >= 20.

Write down the formulation before touching code for any nontrivial problem. Most "solver failures" are formulation errors — a sign flipped in a constraint, a missing nonnegativity bound — and catching them on paper is faster than debugging a solver status code.

Solving with SciPy and HiGHS

SciPy's linprog ships with the HiGHS solver, which is fast, open-source, and production-credible for LPs. Coefficients go in as arrays in the canonical minimization form (negate the objective for maximization).

python
import numpy as np
from scipy.optimize import linprog

# Maximize profit -> minimize negative profit
c = np.array([-40.0, -30.0, -50.0])  # x_A, x_B, x_C

# Inequality constraints (<= form)
A_ub = np.array([
    [2, 1, 3],   # machine hours
    [3, 2, 4],   # material lbs
])
b_ub = np.array([200.0, 400.0])

# Variable bounds encode nonnegativity and the minimum commitments
bounds = [
    (50, None),  # x_A >= 50
    (0, None),   # x_B >= 0
    (20, None),  # x_C >= 20
]

result = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method="highs")

print(f"status: {result.message}")
print(f"x_A={result.x[0]:.1f}, x_B={result.x[1]:.1f}, x_C={result.x[2]:.1f}")
print(f"max profit = ${-result.fun:,.2f}")

# Slack in each constraint: how much of the resource is unused
slacks = b_ub - A_ub @ result.x
print(f"machine slack={slacks[0]:.1f} hrs, material slack={slacks[1]:.1f} lbs")

HiGHS also exposes the dual solution (result.ineqlin.marginals), which we will interpret below. For equality constraints pass A_eq/b_eq; for minimization leave c positive. Always check result.success — a status of 2 means infeasible, 3 means unbounded, each with its own diagnostic path.

Declarative modeling with PuLP

Array-based models are fine for textbook problems; real decisions have dozens of products, SKUs, or lanes and benefit from named variables and constraints. PuLP lets you write the model the way you described it, then dispatches to HiGHS, CBC, or a commercial solver.

python
import pulp

model = pulp.LpProblem("production_planning", pulp.LpMaximize)

products = ["A", "B", "C"]
profit = {"A": 40, "B": 30, "C": 50}
machine = {"A": 2, "B": 1, "C": 3}
material = {"A": 3, "B": 2, "C": 4}
min_commit = {"A": 50, "B": 0, "C": 20}

x = pulp.LpVariable.dicts("produce", products, lowBound=0, cat="Continuous")

model += pulp.lpSum(profit[p] * x[p] for p in products), "total_profit"
model += pulp.lpSum(machine[p] * x[p] for p in products) <= 200, "machine_capacity"
model += pulp.lpSum(material[p] * x[p] for p in products) <= 400, "material_capacity"
for p in products:
    if min_commit[p] > 0:
        model += x[p] >= min_commit[p], f"min_{p}"

model.solve(pulp.HiGHS(msg=False))
print(f"status: {pulp.LpStatus[model.status]}")
for p in products:
    print(f"  {p}: {x[p].value():.1f} units")
print(f"objective = ${pulp.value(model.objective):,.2f}")

PuLP shines for extension: add a binary variable for setup costs (y_p equals 1 if product p is produced at all, with x[p] <= M * y[p] and a fixed cost in the objective), add linking constraints across scenarios, or write a function that builds the model from a dataframe so new products require no code change. The same formulation can be exported to MPS format and audited by operations researchers who do not read Python.

Sensitivity: dual values and reduced costs

The optimal solution is only half the answer. The dual value (shadow price) of a constraint tells you how much the objective improves if you relax that constraint by one unit — the marginal value of an extra machine hour or an extra pound of material. The reduced cost of a variable tells you how much its objective coefficient would need to improve before it becomes worth producing (when currently at zero).

python
import numpy as np
from scipy.optimize import linprog

c = np.array([-40.0, -30.0, -50.0])
A_ub = np.array([[2, 1, 3], [3, 2, 4]])
b_ub = np.array([200.0, 400.0])
bounds = [(50, None), (0, None), (20, None)]

res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bounds, method="highs")

duals = -res.ineqlin.marginals  # HiGHS returns marginals for minimization
print(f"dual machine_hours = ${duals[0]:.2f}/hr")
print(f"dual material_lbs  = ${duals[1]:.2f}/lb")

# Validate: re-solve with one extra hour of machine capacity
b2 = b_ub + np.array([1.0, 0.0])
res2 = linprog(c, A_ub=A_ub, b_ub=b2, bounds=bounds, method="highs")
print(f"profit lift from +1 machine hr = ${-res2.fun - (-res.fun):.2f}")

Dual values drive the business conversation. If an extra machine hour adds <MathBlock tex=15 of profit and overtime costs \ />10/hour, buy overtime up to the point where the dual value falls below the cost (duals are valid in a neighborhood around the optimum — the solver's ranging output tells you how far). Reduced costs answer buy/build questions: a product with a large negative reduced cost is a strong candidate for a process improvement that lowers its effective cost or raises its margin.

Infeasibility, unboundedness, and integrality

Infeasible means no solution satisfies all constraints simultaneously — usually a minimum commitment that exceeds capacity, or two constraints that contradict. Unbounded means the objective can grow without limit — almost always a missing constraint (forgot to cap production, a sign error turning a <= into >=). Diagnose by relaxing constraints one at a time and re-solving; the relaxation that flips the status identifies the culprit. PuLP and commercial solvers can also return an IIS (irreducible infeasible subsystem): a minimal set of constraints that together are inconsistent.

Integer variables turn an LP into a MILP, which is NP-hard in the worst case but routinely solved for thousands of binaries by modern branch-and-cut. Use integrality when decisions are discrete — open or close a warehouse, select at most 3 of 10 campaigns, assign each customer to exactly one treatment. A useful middle ground: solve the LP relaxation first (allow fractional values), read its bound, then add integrality only where the fractional solution is operationally nonsense — often a handful of linking variables, not the entire model.

StatusMeaningFirst debugging step
OptimalFeasible optimum foundRead duals; validate formulation against a toy case
InfeasibleNo feasible pointRelax constraints one at a time; ask for an IIS
UnboundedObjective unboundedLook for a missing upper bound or sign error
Suboptimal / limitTime or node limit hitTighten formulation, warm-start, or accept a bound gap

A decision-science checklist for production LPs

Before shipping an optimization model to influence real decisions, validate it on a hand-solvable toy instance where you know the answer; unit-test the formulation the way you unit-test code. Log the full solution — objective, variable values, duals, solve time — alongside the input snapshot so any decision is auditable months later. Add a slack-variable report to every solve: constraints binding at zero slack are the scarce resources worth measuring more accurately, and a sudden shift in which constraints bind is often the earliest signal that the input data drifted.

Finally, decide what happens when the solver fails or times out in production. A fallback policy (last-known-good solution, a simple greedy heuristic, or a human override queue) is not optional for systems that allocate budget or inventory — the solver returning None at 2 AM is an operational state, not an exception to ignore.

Common Mistakes

Flipping the sign of the objective and forgetting to negate the result back

Fix: Always convert maximization to minimization internally, print the negated objective only at the reporting layer, and unit-test against a known optimum.

Leaving out nonnegativity or logical constraints that make fractional nonsense feasible

Fix: State every variable's bounds explicitly and add linking constraints (big-M or indicator) for setup and assignment logic.

Treating dual values as globally valid when they only hold near the optimum

Fix: Re-solve with the proposed resource change; if the change is large, the dual's neighborhood no longer applies and the marginal value shrinks.

Solving in production without a timeout or fallback policy

Fix: Set time limits, record the achieved bound gap, and define a deterministic fallback before the first live solve.

Best Practices

  • Write the formulation in math or prose before coding; unit-test the model on a toy instance with a known optimal value
  • Use PuLP (or similar) for named, maintainable models that non-authors can audit; reserve raw SciPy arrays for quick analyses
  • Always read duals and reduced costs — they quantify the business value of each scarce resource and guide process investment
  • Diagnose infeasibility with one-at-a-time relaxation or IIS rather than deleting constraints randomly
  • Log solution, duals, bound gap, and input snapshot for every production solve to enable audit and drift detection

Interview Questions

Q1: What does the dual value of a capacity constraint represent in business terms?

The marginal value of one additional unit of that capacity — for example, the profit lift from one extra machine hour at the current optimum. If the dual exceeds the cost of acquiring more capacity, expanding is economically justified (within the dual's valid range).

Q2: How do you debug an infeasible LP?

Relax constraints one at a time and re-solve to find which binding pair causes conflict, or ask the solver for an irreducible infeasible subsystem (IIS) — a minimal inconsistent subset. Common causes are minimum commitments exceeding capacity or contradictory lower/upper bounds.

Q3: When should you use integer variables instead of a pure LP?

When decisions are inherently discrete — open/close facilities, select subsets, assign each entity to exactly one option. Start with the LP relaxation to get a bound, then add integrality only where fractional values are operationally meaningless.

Key Takeaways

  • Formulation — variables, objective, constraints — is the real skill; solvers are fast and interchangeable, bad formulations are not
  • SciPy linprog (HiGHS) suits quick array-based solves; PuLP suits maintainable, auditable production models with named structure
  • Dual values quantify the marginal value of scarce resources; reduced costs tell you when a zero variable would become worth producing
  • Infeasible and unbounded statuses are formulation bugs, not solver bugs — debug with relaxation or IIS
  • Production LPs need timeouts, fallback policies, and logged duals alongside solutions for audit and drift detection
🔒

Premium Content

Optimization and Linear Programming for Decision Science

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Continue Learning

Suggested next tutorials based on this topic

Advertisement