23.1 The model
candidate_sites lists 10 sites; site_store_lanes the cost per pallet from each to each store, computed like Day 14's lanes. Decisions: if site runs; the share of store 's pallets that come from site .
The French-label and six-hour rules from Day 15 fix the forbidden to 0. Create day23/facility.py:
"""Day 23: facility location. Which sites to run, and which stores each one serves.
Import it: from facility import load_sites, build_location, summary
"""
import pandas as pd
import pyomo.environ as pyo
MAX_MINUTES = 360
def load_sites(con):
sites = con.sql("SELECT * FROM candidate_sites ORDER BY site_id").df().set_index("site_id")
stores = con.sql("""SELECT s.store_id, s.city, s.province, l.pallets_per_week
FROM stores s JOIN store_logistics l USING (store_id) ORDER BY s.store_id""").df().set_index("store_id")
lanes = con.sql("SELECT * FROM site_store_lanes").df().set_index(["site_id", "store_id"])
return sites, stores, lanes
def build_location(sites, stores, lanes, capacitated=True, single_source=True, domain=pyo.Binary, fixed_scale=1.0):
"""open[i] = 1 if site i runs (and pays its weekly fixed cost);
serve[i, j] = share of store j's pallets that come from site i (0 or 1 with single sourcing)."""
m = pyo.ConcreteModel(name="facility_location")
m.I = pyo.Set(initialize=sites.index.tolist())
m.J = pyo.Set(initialize=stores.index.tolist())
m.open = pyo.Var(m.I, within=domain)
serve_domain = pyo.Binary if (single_source and domain is pyo.Binary) else pyo.UnitInterval
m.serve = pyo.Var(m.I, m.J, within=serve_domain)
m.every_store = pyo.Constraint(m.J, rule=lambda m, j: sum(m.serve[i, j] for i in m.I) == 1)
m.only_if_open = pyo.Constraint(m.I, m.J, rule=lambda m, i, j: m.serve[i, j] <= m.open[i])
if capacitated:
m.capacity = pyo.Constraint(m.I, rule=lambda m, i: sum(stores.pallets_per_week[j] * m.serve[i, j] for j in m.J)
<= sites.capacity_pallets[i] * m.open[i])
for i in m.I:
for j in m.J:
if (stores.province[j] == "QC" and not sites.ships_french_labels[i]) or lanes.minutes[i, j] > MAX_MINUTES:
m.serve[i, j].fix(0)
m.fixed = pyo.Expression(expr=fixed_scale * sum(sites.fixed_cost_per_week[i] * m.open[i] for i in m.I))
m.transport = pyo.Expression(expr=sum(lanes.cost_per_pallet[i, j] * stores.pallets_per_week[j] * m.serve[i, j]
for i in m.I for j in m.J))
m.cost = pyo.Objective(expr=m.fixed + m.transport)
return m
def summary(m, sites, stores):
rows = []
for i in m.I:
if pyo.value(m.open[i]) > 1e-6:
load = sum(stores.pallets_per_week[j] * pyo.value(m.serve[i, j]) for j in m.J)
n = sum(pyo.value(m.serve[i, j]) > 1e-6 for j in m.J)
rows.append((i, sites.place[i], round(pyo.value(m.open[i]), 3) + 0.0, n, round(load, 1), sites.capacity_pallets[i]))
return pd.DataFrame(rows, columns=["site", "place", "open", "stores", "pallets", "capacity"])
The constraint only_if_open is a big-M constraint with M = 1, the tightest possible: a store can take at most all of its pallets from a site, and only if it's open.
Then day23/run_location.py, starting with today's network: open the three DCs, close the candidates, and let the model assign stores.
import sys
import duckdb
import pandas as pd
import pyomo.environ as pyo
sys.path.insert(0, "day23")
from facility import build_location, load_sites, summary
pd.set_option("display.width", 140)
con = duckdb.connect("northbound.duckdb", read_only=True)
sites, stores, lanes = load_sites(con)
solver = pyo.SolverFactory("highs")
print(sites.to_string())
def run(label, **kw):
m = build_location(sites, stores, lanes, **kw)
solver.solve(m)
print(f"--- {label}: ${pyo.value(m.cost):,.2f} a week = fixed ${pyo.value(m.fixed):,.0f} + transport ${pyo.value(m.transport):,.2f}")
print(summary(m, sites, stores).to_string(index=False))
return m
# ---------- 23.1 Today's network as a location model ----------
today = build_location(sites, stores, lanes)
for i in today.I:
today.open[i].fix(1 if i.startswith("DC-") else 0)
solver.solve(today)
print(f"--- today's three DCs, single sourcing: ${pyo.value(today.cost):,.2f} a week = fixed ${pyo.value(today.fixed):,.0f} "
f"+ transport ${pyo.value(today.transport):,.2f}")
place kind fixed_cost_per_week capacity_pallets ships_french_labels
site_id
DC-MIS Mississauga existing DC 21000 1600 0
DC-MTL Montreal existing DC 19000 1500 1
DC-OTT Ottawa existing DC 11000 700 1
NEW-BRA Brampton candidate 23000 1800 0
NEW-COR Cornwall candidate 12000 1000 1
NEW-DRU Drummondville candidate 12500 900 1
NEW-HAM Hamilton candidate 16000 1100 0
NEW-KIN Kingston candidate 12500 900 0
NEW-LAV Laval candidate 20000 1300 1
NEW-QUE Quebec City candidate 13500 700 1
--- today's three DCs, single sourcing: $92,492.76 a week = fixed $51,000 + transport $41,492.76
Today's three DCs, with single sourcing: $92,492.76 a week: $51,000 of fixed costs and Day 15's $41,492.76 of transport.
23.2 Uncapacitated, capacitated, single-sourced
Now let the model choose the sites, in three versions of increasing realism:
# ---------- 23.2 Uncapacitated, capacitated, single-sourced ----------
run("no capacity limits", capacitated=False, single_source=False)
run("capacity limits, stores may be split", single_source=False)
best = run("capacity limits, one site per store")
--- no capacity limits: $85,450.50 a week = fixed $46,000 + transport $39,450.50
site place open stores pallets capacity
DC-MTL Montreal 1.0 15 1427.0 1500
DC-OTT Ottawa 1.0 10 923.0 700
NEW-HAM Hamilton 1.0 15 1195.0 1100
--- capacity limits, stores may be split: $90,089.81 a week = fixed $51,000 + transport $39,089.81
site place open stores pallets capacity
DC-MIS Mississauga 1.0 18 1345.0 1600
DC-MTL Montreal 1.0 16 1500.0 1500
DC-OTT Ottawa 1.0 8 700.0 700
--- capacity limits, one site per store: $92,492.76 a week = fixed $51,000 + transport $41,492.76
site place open stores pallets capacity
DC-MIS Mississauga 1.0 17 1365.0 1600
DC-MTL Montreal 1.0 16 1480.0 1500
DC-OTT Ottawa 1.0 7 700.0 700
- Without capacities, Hamilton replaces Mississauga: it is cheaper to run ($16,000 against $21,000), and Toronto stores are close to both. But Hamilton then ships 1,195 pallets with room for 1,100, and Ottawa ships 923 with room for 700. The uncapacitated model is the classic textbook one, and its answer here is impossible.
- With capacities, the model keeps today's three DCs: $90,089.81 with split stores, $92,492.76 with single sourcing. None of the seven candidates pays for itself.
The finding: today's network is the right one at today's costs and volumes. A network study that confirms the current network is a real result: it saves the cost of a move, and tells you what would have to change for a move to pay (23.4).
Decision it supports: which sites to run, and which customers each serves.
Other decisions you can support the same way: where to put ambulance stations, schools, cell towers or charging stations · which warehouses to keep after a merger.
23.3 The relaxation, and why it can mislead
# ---------- 23.3 The relaxation, and why it can mislead ----------
run("relaxation: open and serve may be fractions", domain=pyo.UnitInterval)
--- relaxation: open and serve may be fractions: $89,717.62 a week = fixed $51,243 + transport $38,474.27
site place open stores pallets capacity
DC-MIS Mississauga 1.00 17 1326.3 1600
DC-MTL Montreal 1.00 16 1500.0 1500
DC-OTT Ottawa 1.00 8 700.0 700
NEW-COR Cornwall 0.02 10 18.7 1000
The relaxation "opens 2% of Cornwall" for $243 a week and splits ten stores between Cornwall and their DC. Its bound, $89,717.62, is 3% below the best plan. For this model the relaxation is fairly tight because only_if_open links each store to each site separately (the strong formulation). Day 27 compares it with a weaker but common alternative (one constraint per site instead of one per store and site) and shows the difference in search effort.
23.4 How close is each candidate?
A MIP has no reduced costs for its binaries. To learn how far each candidate is from being worth opening, force it open and re-solve: the extra cost is what it would take to justify it.
# ---------- 23.4 How close is each candidate? Force it open ----------
rows = []
for i in sites.index[sites.kind == "candidate"]:
m = build_location(sites, stores, lanes)
m.open[i].fix(1)
solver.solve(m)
extra = pyo.value(m.cost) - pyo.value(best.cost)
rows.append((i, sites.place[i], sites.fixed_cost_per_week[i], round(extra, 2),
round(sites.fixed_cost_per_week[i] - extra, 2), ", ".join(x for x in m.I if pyo.value(m.open[x]) > 0.5)))
force = pd.DataFrame(rows, columns=["candidate", "place", "fixed_cost", "extra_cost_if_opened", "break_even_fixed_cost", "network"])
print(force.sort_values("extra_cost_if_opened").to_string(index=False))
candidate place fixed_cost extra_cost_if_opened break_even_fixed_cost network
NEW-QUE Quebec City 13500 2656.20 10843.80 DC-MIS, DC-MTL, DC-OTT, NEW-QUE
NEW-COR Cornwall 12000 3880.35 8119.65 DC-MIS, DC-MTL, NEW-COR
NEW-BRA Brampton 23000 4200.99 18799.01 DC-MTL, DC-OTT, NEW-BRA
NEW-DRU Drummondville 12500 4708.70 7791.30 DC-MIS, DC-MTL, DC-OTT, NEW-DRU
NEW-KIN Kingston 12500 5558.45 6941.55 DC-MIS, DC-MTL, DC-OTT, NEW-KIN
NEW-LAV Laval 20000 5588.02 14411.98 DC-MIS, DC-OTT, NEW-LAV, NEW-QUE
NEW-HAM Hamilton 16000 7102.24 8897.76 DC-MTL, DC-OTT, NEW-HAM, NEW-KIN
- Quebec City is closest: opening it costs $2,656 a week more than today's network. If its weekly cost fell from $13,500 to $10,844 (a cheaper lease, a shared building), it would pay.
- Cornwall is the interesting one: forced open, the model closes Ottawa and serves the Ottawa region from Cornwall, which has room for all 923 pallets. It costs $3,880 a week more than today, but fixes Ottawa's capacity problem: see the mini-project.
- Brampton, forced open, replaces Mississauga; Laval, forced open, replaces Montreal and brings Quebec City along. Forcing one site open shows the whole network reorganizing around it.
The planted bug
day23/bug_link.py drops one constraint from the uncapacitated model, "because without capacity rows we don't need it". Run it.
con = duckdb.connect("northbound.duckdb", read_only=True)
sites, stores, lanes = load_sites(con)
m = build_location(sites, stores, lanes, capacitated=False, single_source=False)
m.del_component(m.only_if_open) # "with no capacity rows, we don't need it"
pyo.SolverFactory("highs").solve(m)
print(f"${pyo.value(m.cost):,.2f} a week = fixed ${pyo.value(m.fixed) + 0.0:,.0f} + transport ${pyo.value(m.transport):,.2f}")
opened = summary(m, sites, stores)
print("open sites:", opened.site.tolist())
served_by_closed = sum(pyo.value(m.serve[i, j]) > 1e-6 and pyo.value(m.open[i]) < 0.5 for i in m.I for j in m.J)
print(f"store deliveries from sites that are closed: {served_by_closed}")
What happens, and why
$20,648.86 a week = fixed $0 + transport $20,648.86
open sites: []
store deliveries from sites that are closed: 40
No site is open, no fixed cost is paid, and every store is served, from closed sites. Without only_if_open, nothing ties deliveries to open sites; in the capacitated model the capacity row happens to do that job (), which is why the bug only shows when capacities are removed. Every link between a yes/no decision and the quantities it controls must be in the model explicitly.
Mini-project: should Ottawa close?
The Ottawa DC is over capacity (Day 14), and a board member asks whether to close it. Compare: the best network; Ottawa closed with no new site; Ottawa closed with any candidate allowed; Ottawa replaced by Cornwall; Ottawa replaced by Kingston. Recommend.
Solution
import sys
import duckdb
import pyomo.environ as pyo
sys.path.insert(0, "day23")
from facility import build_location, load_sites, summary
con = duckdb.connect("northbound.duckdb", read_only=True)
sites, stores, lanes = load_sites(con)
solver = pyo.SolverFactory("highs")
def scenario(label, fixes):
m = build_location(sites, stores, lanes)
for i, v in fixes.items():
m.open[i].fix(v)
result = solver.solve(m, load_solutions=False)
if result.solver.termination_condition != pyo.TerminationCondition.optimal:
print(f"--- {label}: {result.solver.termination_condition}")
return None
m.solutions.load_from(result)
print(f"--- {label}: ${pyo.value(m.cost):,.2f} a week (fixed ${pyo.value(m.fixed):,.0f}, transport ${pyo.value(m.transport):,.2f})")
print(summary(m, sites, stores).to_string(index=False))
return pyo.value(m.cost)
candidates = {i: 0 for i in sites.index if sites.kind[i] == "candidate"}
best = scenario("best network", {})
scenario("close Ottawa, no new site", {"DC-OTT": 0, **candidates})
scenario("close Ottawa, any candidate may open", {"DC-OTT": 0})
scenario("close Ottawa, open Cornwall", {"DC-OTT": 0, **candidates, "NEW-COR": 1})
scenario("close Ottawa, open Kingston", {"DC-OTT": 0, **candidates, "NEW-KIN": 1})
--- best network: $92,492.76 a week (fixed $51,000, transport $41,492.76)
site place open stores pallets capacity
DC-MIS Mississauga 1.0 17 1365.0 1600
DC-MTL Montreal 1.0 16 1480.0 1500
DC-OTT Ottawa 1.0 7 700.0 700
--- close Ottawa, no new site: infeasible
--- close Ottawa, any candidate may open: $96,373.11 a week (fixed $52,000, transport $44,373.11)
site place open stores pallets capacity
DC-MIS Mississauga 1.0 15 1195.0 1600
DC-MTL Montreal 1.0 15 1427.0 1500
NEW-COR Cornwall 1.0 10 923.0 1000
--- close Ottawa, open Cornwall: $96,373.11 a week (fixed $52,000, transport $44,373.11)
site place open stores pallets capacity
DC-MIS Mississauga 1.0 15 1195.0 1600
DC-MTL Montreal 1.0 15 1427.0 1500
NEW-COR Cornwall 1.0 10 923.0 1000
--- close Ottawa, open Kingston: infeasible
- Closing Ottawa without a replacement is impossible: Mississauga and Montreal can't take 3,545 pallets.
- Kingston can't replace Ottawa either: it has no French-labelled stock, so the Ottawa region's Quebec stores would have to come from Montreal, which has only 20 pallets of room.
- Cornwall can: it takes exactly the 10 Ottawa-region stores (923 pallets), with room to spare. The network costs $96,373.11, $3,880 a week more than keeping Ottawa.
Memo to the board: "Keep the Ottawa DC. Replacing it with a new Cornwall site would cost about $3,900 a week more ($200,000 a year), before any move costs. Ottawa's real problem is capacity, not location: Day 15 found that 100 more pallets of capacity in Ottawa saves $4,800 a week. Expand Ottawa before considering a new site. Revisit if Cornwall's cost falls below about $8,100 a week."
Commit
git add .
git commit -m "Day 23: facility location"
git push
Then run the tests: tests/test_integer.py checks Days 21–23 (the investment MIP against enumeration, the relaxation bound, minimum runs, and the location model). Add "day21", "day22", "day23" to the folders in conftest.py.
"""Module 3, Days 21-23: binary decisions, fixed costs and facility location."""
import itertools
import pyomo.environ as pyo
import pytest
from bakery import load_data, solve
from facility import build_location, load_sites
from investments import build_with_investments
from setup_model import build_with_setups
TOL = 1e-6
@pytest.fixture(scope="module")
def range_data(con):
return load_data(con)
def test_investment_mip_matches_enumeration(con, range_data):
menu = con.sql("SELECT * FROM bakery_investments").df().set_index("option")
m = build_with_investments(range_data, menu)
solve(m)
best = -1
for choice in itertools.product([0, 1], repeat=len(menu)):
e = build_with_investments(range_data, menu)
for o, c in zip(menu.index, choice):
e.buy[o].fix(c)
solve(e)
best = max(best, pyo.value(e.net_profit))
assert pyo.value(m.net_profit) == pytest.approx(best, abs=0.01) == pytest.approx(113_488.16, abs=0.01)
def test_relaxation_is_an_upper_bound(con, range_data):
menu = con.sql("SELECT * FROM bakery_investments").df().set_index("option")
exact, relaxed = build_with_investments(range_data, menu), build_with_investments(range_data, menu, pyo.UnitInterval)
solve(exact)
solve(relaxed)
assert pyo.value(relaxed.net_profit) >= pyo.value(exact.net_profit) - TOL
def test_setups_respect_minimum_runs(con, range_data):
setup = con.sql("SELECT * FROM bakery_range_setup").df().set_index("sku")
m = build_with_setups(range_data, setup)
solve(m)
assert pyo.value(m.net_profit) == pytest.approx(102_242.38, abs=0.01)
for p in m.P:
x = pyo.value(m.x[p])
assert x < TOL or x >= setup.min_batches_if_made[p] - TOL
def test_location_keeps_todays_network_and_serves_every_store_once(con):
sites, stores, lanes = load_sites(con)
m = build_location(sites, stores, lanes)
pyo.SolverFactory("highs").solve(m)
assert pyo.value(m.cost) == pytest.approx(92_492.76, abs=0.01)
assert sorted(i for i in m.I if pyo.value(m.open[i]) > 0.5) == ["DC-MIS", "DC-MTL", "DC-OTT"]
for j in m.J:
assert sum(round(pyo.value(m.serve[i, j])) for i in m.I) == 1
40 passed
Day 23 checklist
- I can write a facility location model with fixed costs, capacities and single sourcing.
- I know why the uncapacitated model can give impossible answers.
- I can say when a location study confirming today's network is a real result.
- I priced each candidate by forcing it open, and computed its break-even cost.
- I know every yes/no decision must be linked explicitly to what it controls.
- I answered the board's question with feasible and infeasible scenarios, and a recommendation.