Each example solves the same problem in Python (PuLP) and R (lpSolve / ompr). The solutions are always identical — LP is deterministic. The interest is in how each language expresses the model.
At the end of each example you will find a 💬 Explore with an LLM block. These are ready-to-use prompts you can paste directly into any AI assistant (ChatGPT, Claude, Amazon Q, etc.) to go deeper on the key concept from that example. They are written to build on what you just read, not to replace it.
A manufacturer makes wine and beer glasses. Each consumes machine time and raw materials. Maximise profit.
| Wine | Beer | |
|---|---|---|
| Profit/batch | $5 | $4.50 |
| Machine hrs | 6 | 5 |
| Raw material | 10 | 20 |
Constraints: machine ≤ 60 hrs, material ≤ 150 units, wine batches ≤ 6.
Key concept: The simplest possible integer LP. Good first model to read in both languages.
Python names variables explicitly and adds constraints one at a time:
wine = LpVariable('Wine', lowBound=0, cat='Integer')
model += 6 * wine + 5 * beer <= 60R supplies everything as matrices and vectors up front:
obj <- c(5, 4.5)
const.mat <- rbind(c(6,5), c(10,20), c(1,0))
lp("max", obj, const.mat, rep("<=", 3), c(60, 150, 6), all.int=TRUE)The R approach requires you to keep the column order of the constraint matrix in your head — column 1 is wine, column 2 is beer, and nothing in the code reminds you of that. PuLP's named variables remove that ambiguity. However, PuLP also hides the matrix structure entirely, which is actually what the solver operates on. Both approaches obscure something: one hides variable identity, the other hides the underlying linear algebra. Which matters more depends on whether your goal is readable code or understanding what the solver is actually doing.
💬 Explore with an LLM "I just ran the glass factory LP example. Can you show me what the constraint matrix looks like for this problem, and explain how a solver uses it to find the optimal solution?"
A bakery makes two cakes. Maximise revenue subject to oven time, labour, and ingredient limits.
| Cake A | Cake B | |
|---|---|---|
| Revenue | $20 | $40 |
| Oven (hrs) | 0.5 | 1 |
| Labour (hrs) | 1 | 2.5 |
| Ingredients | 1 | 2 |
Key concept: Corner solutions. In the glass factory, the market constraint (wine <= 6) prevents a pure corner — without it the solver would dump everything into wine. Here, no constraint intervenes: the solver pushes entirely into Cake B (the higher-revenue product), producing a pure corner solution.
This matters because simple objectives naturally drive toward corners. In real problems, trade-offs are less clear and multiple constraints interact to pull the solution away from the naive heuristic. Recognising when a corner solution is "real" vs when it signals a missing constraint is a core optimisation skill.
💬 Explore with an LLM "The bakery LP produces a corner solution — the solver puts everything into the higher-revenue product. Can you explain what corner solutions are geometrically, why LP solvers always find them, and how adding constraints can pull the optimum away from a corner?"
Maximise 4X + 3Y with continuous variables (Y has a lower bound of 2).
Key concept: Switching from integer to continuous LP. R's bakP2.R also demonstrates linprog::solveLP as an alternative solver and shows how to request sensitivity analysis with compute.sens=1 — something PuLP requires extra steps for.
💬 Explore with an LLM "What is sensitivity analysis in linear programming and why is it useful? Given the constraint
2Y <= 25 - X, what would it tell me if I asked how much the optimal solution changes if that right-hand side increases from 25 to 26?"
Two car models, profits of $30k and $45k, three resource constraints. Maximise profit.
Key concept: The LP structure is identical to the bakery — only the numbers change. Useful for confirming that the model pattern generalises regardless of scale.
💬 Explore with an LLM "The car factory and bakery problems have identical LP structure but very different numbers. What properties of a problem determine whether LP will find a good solution, regardless of the scale of the coefficients?"
Minimise cost of blending pork, wheat, and starch into economy and premium sausages. Percentage quality constraints apply.
Key concept: A classic blending problem. Percentage constraints must be rewritten as linear inequalities, e.g.:
pork >= 0.4 * total → 0.6*pork - 0.4*wheat - 0.4*starch >= 0
This is where the two approaches diverge most visibly at small scale. PuLP uses a 2D variable dictionary indexed by (sausage_type, ingredient):
ing_weight = LpVariable.dicts("weight kg",
((i, j) for i in sausage_types for j in ingredients), lowBound=0)
model += ing_weight['economy', 'pork'] >= 0.4 * lpSum([ing_weight['economy', j] for j in ingredients])R requires manually laying out a 10×6 constraint matrix — more error-prone, but it makes the linear algebra explicit.
💬 Explore with an LLM "In the sausage blending problem, the constraint 'economy sausages must be at least 40% pork' gets rewritten as a linear inequality. Can you walk me through that algebra step by step, and explain why percentage constraints always need to be rewritten this way?"
Two factories must meet 12 months of demand. Each has variable costs, fixed costs, min/max capacity. Factory B is shut in May. Minimise total cost.
Data: data/fac_vars.csv, data/demand.csv
Key concept: First full MIP — binary factory_status variables act as on/off switches. Capacity constraints are linked to status:
production >= min_capacity * status
production <= max_capacity * status
If status = 0, both constraints force production = 0.
This is also where the R library choice shifts from lpSolve to ompr, which uses a pipe-based declarative style much closer to how you'd write the maths:
MIPModel() %>%
add_variable(prod[i, j], i=months, j=factories, type="integer") %>%
add_constraint(sum_expr(prod[i, j], j=factories) == demand[i], i=months)vs Python's imperative loop:
for month in months:
model += production[(month, 'A')] + production[(month, 'B')] == demand.loc[month, 'Demand']Both are readable; ompr's index-set style is closer to mathematical notation.
💬 Explore with an LLM "In the factory scheduling MIP, a binary variable is used as an on/off switch linked to production via
production >= min_capacity * status. Can you explain why multiplying a continuous variable by a binary variable is such a powerful modelling trick, and where else this pattern appears in real-world optimisation?"
Extends example 6 with a one-time startup cost when a factory switches from off to on (A: $20k, B: $400k).
Key concept: Detecting a 0→1 transition requires a new binary variable switch_on and three constraints per factory per month:
switch_on[m] >= status[m] - status[m-1] # fires on transition
switch_on[m] <= 1 - status[m-1] # can't fire if already on
switch_on[m] <= status[m] # can't fire if currently off
The R version (bakP6.R) uses Rsymphony with a manually built constraint matrix. The Python version expresses the same logic in a loop with fewer lines. From a software perspective PuLP is more concise — but the Rsymphony version forces you to construct the exact object the solver operates on, which means you cannot write it without understanding the underlying linear algebra. Which version is "better" depends entirely on your goal: writing working code quickly, or understanding what the solver is actually doing.
💬 Explore with an LLM "The startup cost problem uses three constraints to detect a 0→1 transition in a binary variable. Can you explain intuitively why you need three constraints rather than one, and draw out a truth table showing what each constraint rules out?"
⚠️ Run order:omprTSP.RandomprTSPwithSymp.Rboth read fromdata/tsp_cities.csv. This file is already included in the repo — no pre-run step needed. If you delete it and want to regenerate it, runomprTSP.Rfirst.
Find the shortest route visiting 10 randomly placed cities exactly once.
Key concept: Classic combinatorial optimisation. The tricky part is subtour elimination — without it, the solver finds multiple disconnected loops. The Miller-Tucker-Zemlin (MTZ) constraint handles this:
u[i] - u[j] + 1 <= (n-1) * (1 - x[i,j])
This forces a consistent city ordering, ruling out sub-loops.
All three implementations (tsp_pulp.py, omprTSP.R, omprTSPwithSymp.R) read from the same data/tsp_cities.csv and produce the same optimal distance (1469.86).
💬 Explore with an LLM "The TSP uses Miller-Tucker-Zemlin constraints to eliminate subtours. Can you show me a small example — say 4 cities — where without these constraints the solver would return an invalid solution with two disconnected loops, and then show how the MTZ constraints rule it out?"
⚠️ Run order: All three files read fromdata/assign_prefs.csv. This file is already included in the repo — no pre-run step needed. If you delete it and want to regenerate it, runassignStudents.Rfirst (it usesset.seed(1234)).
Assign 40 students to 4 courses (capacity 11 each) to maximise preference satisfaction. Each student ranks 3 courses.
Key concept: An assignment problem — binary x[i,j] = 1 if student i goes to course j. Each student gets exactly one course; each course has a cap. Unranked courses get a large negative weight to discourage assignment.
All three implementations read from the same data/assign_prefs.csv and produce the same objective value.
💬 Explore with an LLM "The student assignment problem uses a large negative weight (-10000) for unranked courses to discourage assignment. What are the risks of this approach compared to adding a hard constraint that prevents unranked assignments entirely?"
⚠️ warehouse_location.pyis a stub — not yet implemented. See TODO.
100 customers, 20 potential warehouse sites each with a fixed build cost. Choose which to build and which customers to assign, minimising transport + fixed costs.
Key concept: Facility location — a common real-world MIP pattern. The key constraint links customer assignment to warehouse existence:
x[i,j] <= y[j]
You can only assign a customer to a warehouse if that warehouse is built. The solver balances paying the fixed cost against the transport savings.
💬 Explore with an LLM "The warehouse location problem has both a fixed cost (building the warehouse) and a variable cost (transport per customer). Can you explain how the solver decides whether the fixed cost of opening a warehouse is worth it, and what real-world problems share this same fixed-vs-variable cost structure?"
⚠️ graph_colouring.pyis a stub — not yet implemented. See TODO.
Colour a US state map so no two adjacent states share a colour, using the fewest colours.
Key concept: Graph colouring as a MIP. Adjacency data comes from a GeoJSON shapefile via spdep::poly2nb. The objective minimise sum(k * y[k]) uses a weighted sum to push the solver toward lower-numbered colours, which naturally minimises the total count used.
This example sits at the boundary of this project's scope. Graph colouring is a classical problem in graph theory — a field concerned with networks of nodes and edges rather than resource allocation or scheduling. Including it here is intentional: it shows that the MIP framework is not limited to operations research problems. Any problem that can be expressed as linear constraints over binary variables is fair game, regardless of the domain it comes from.
If this sparks your interest, graph theory and combinatorial optimisation is a rich area worth exploring separately. A good starting point is the concept of NP-completeness — graph colouring is one of the canonical NP-complete problems, which is part of what makes it interesting to solve with MIP.
💬 Explore with an LLM "Graph colouring is described as NP-complete. Linear programming problems are not. So how is it possible to solve a graph colouring problem using LP/MIP? What does that tell us about the relationship between NP-complete problems and integer programming?"