30.1 The brief
- Demand: each store's pallets (Day 14) grow 3% a year from 2027 to 2031.
- Sites: Day 23's three DCs and seven candidates. An existing DC can close (one-time cost $1.5 million: severance and lease exit); a new site can open (one-time $3 million: fit-out and moving) and pays its weekly fixed cost from then on.
- Expansions (
network_options): Ottawa +300 pallets a week ($1.4 million once, $2,500 a week), Montreal +300 ($1.8 million, $3,000), Mississauga +400 ($2 million, $3,200). - Rules: as on Day 23: single sourcing each year, French labels, six hours on the road.
- Cost case: present value at the start of 2027, discounted at 8% a year; 52 weeks a year.
The model is Day 23's location model with a year index, plus Day 21's yes/no logic for timing: an existing DC that closes stays closed, a new site that opens stays open, an expansion stays built, and one-time costs are paid in the year something changes. Create day30/redesign.py:
"""Day 30 capstone: redesign the DC network for the next five years.
Which sites run each year, which expansions to build and when, which site serves each store each year.
Import it: from redesign import load_redesign, build_redesign, yearly_table
"""
import pyomo.environ as pyo
import pandas as pd
MAX_MINUTES = 360
def load_redesign(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"])
options = con.sql("SELECT * FROM network_options ORDER BY option_id").df().set_index("option_id")
settings = {k: v for k, v in con.sql("SELECT setting, value FROM network_settings").fetchall()}
return sites, stores, lanes, options, settings
def build_redesign(sites, stores, lanes, options, settings, years=None, growth=None, rate=None,
allowed_options=None, allow_new_sites=True, allow_closing=True):
"""Minimize the present value of five years of network costs (52 weeks a year, discounted to the start of 2027)."""
years = int(years or settings["years"])
growth = settings["growth_per_year"] if growth is None else growth
rate = settings["discount_rate"] if rate is None else rate
weeks = settings["weeks_per_year"]
m = pyo.ConcreteModel(name="network_redesign")
m.I = pyo.Set(initialize=sites.index.tolist())
m.J = pyo.Set(initialize=stores.index.tolist())
m.T = pyo.RangeSet(1, years)
m.E = pyo.Set(initialize=[e for e in options.index if allowed_options is None or e in allowed_options])
existing = [i for i in m.I if sites.kind[i] == "existing DC"]
pv = {t: 1 / (1 + rate) ** (t - 1) for t in m.T} # costs of year t valued at the start of year 1
demand = {(j, t): stores.pallets_per_week[j] * (1 + growth) ** (t - 1) for j in m.J for t in m.T}
m.open = pyo.Var(m.I, m.T, within=pyo.Binary)
m.change = pyo.Var(m.I, m.T, within=pyo.NonNegativeReals) # 1 in the year a site opens or closes
m.built = pyo.Var(m.E, m.T, within=pyo.Binary) # expansion in place in year t
m.build = pyo.Var(m.E, m.T, within=pyo.NonNegativeReals) # 1 in the year it is built
m.serve = pyo.Var(m.I, m.J, m.T, within=pyo.Binary)
def before(m, i, t):
return (1 if i in existing else 0) if t == 1 else m.open[i, t - 1]
m.new_stay_open = pyo.Constraint([(i, t) for i in m.I for t in m.T if i not in existing],
rule=lambda m, i, t: m.open[i, t] >= before(m, i, t))
m.closed_stay_closed = pyo.Constraint([(i, t) for i in existing for t in m.T],
rule=lambda m, i, t: m.open[i, t] <= before(m, i, t))
m.count_change = pyo.Constraint(m.I, m.T, rule=lambda m, i, t: m.change[i, t] >= (m.open[i, t] - before(m, i, t)) *
(1 if i not in existing else -1))
if not allow_new_sites:
for i in m.I:
if i not in existing:
for t in m.T:
m.open[i, t].fix(0)
if not allow_closing:
for i in existing:
for t in m.T:
m.open[i, t].fix(1)
m.expansion_stays = pyo.Constraint(m.E, m.T, rule=lambda m, e, t: pyo.Constraint.Skip if t == 1
else m.built[e, t] >= m.built[e, t - 1])
m.count_build = pyo.Constraint(m.E, m.T, rule=lambda m, e, t: m.build[e, t] >= m.built[e, t] - (0 if t == 1 else m.built[e, t - 1]))
m.expand_open_site = pyo.Constraint(m.E, m.T, rule=lambda m, e, t: m.built[e, t] <= m.open[options.site_id[e], t])
m.every_store = pyo.Constraint(m.J, m.T, rule=lambda m, j, t: sum(m.serve[i, j, t] for i in m.I) == 1)
m.only_if_open = pyo.Constraint(m.I, m.J, m.T, rule=lambda m, i, j, t: m.serve[i, j, t] <= m.open[i, t])
m.capacity = pyo.Constraint(m.I, m.T, rule=lambda m, i, t:
sum(demand[j, t] * m.serve[i, j, t] for j in m.J)
<= sites.capacity_pallets[i] * m.open[i, t]
+ sum(options.extra_pallets[e] * m.built[e, t] for e in m.E if options.site_id[e] == 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:
for t in m.T:
m.serve[i, j, t].fix(0)
m.weekly = pyo.Expression(m.T, rule=lambda m, t:
sum(sites.fixed_cost_per_week[i] * m.open[i, t] for i in m.I)
+ sum(options.weekly_cost[e] * m.built[e, t] for e in m.E)
+ sum(lanes.cost_per_pallet[i, j] * demand[j, t] * m.serve[i, j, t] for i in m.I for j in m.J))
m.one_time = pyo.Expression(m.T, rule=lambda m, t:
sum((settings["close_cost_existing_dc"] if i in existing else settings["open_cost_new_site"])
* m.change[i, t] for i in m.I)
+ sum(options.one_time_cost[e] * m.build[e, t] for e in m.E))
m.pv = pyo.Objective(expr=sum(pv[t] * (weeks * m.weekly[t] + m.one_time[t]) for t in m.T))
m.demand = demand
return m
def yearly_table(m, sites, options):
rows = []
for t in m.T:
running = [i for i in m.I if pyo.value(m.open[i, t]) > 0.5]
built = [e for e in m.E if pyo.value(m.built[e, t]) > 0.5]
pallets = sum(m.demand[j, t] for j in m.J)
cap = sum(sites.capacity_pallets[i] for i in running) + sum(options.extra_pallets[e] for e in built)
rows.append((2026 + t, round(pallets), cap, ", ".join(i.split("-")[1] for i in running), ", ".join(built) or "-",
round(pyo.value(m.weekly[t]), 2), round(pyo.value(m.one_time[t])) + 0))
return pd.DataFrame(rows, columns=["year", "pallets_a_week", "capacity", "sites", "expansions", "weekly_cost", "one_time"])
Every year's costs are multiplied by : a dollar spent in 2031 is worth 74 cents today. Then day30/network_plan.py, starting with a known-answer check: one year, no growth, nothing to build must give Day 23's network at 52 times its weekly cost.
for folder in ("day23", "day26", "day30"):
sys.path.insert(0, folder)
from facility import build_location
from highs_run import run_highs
from redesign import build_redesign, load_redesign, yearly_table
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
sites, stores, lanes, options, settings = load_redesign(con)
solver = pyo.SolverFactory("highs")
print(options.to_string())
print(settings)
# ---------- 30.1 Check: one year, no growth = Day 23 ----------
m = build_redesign(sites, stores, lanes, options, settings, years=1, growth=0)
solver.solve(m)
print(f"one year, no growth: ${pyo.value(m.pv):,.2f} = 52 x ${pyo.value(m.pv) / 52:,.2f} a week (Day 23: $92,492.76)")
site_id kind extra_pallets one_time_cost weekly_cost
option_id
EXP-MIS DC-MIS expand 400 2000000 3200
EXP-MTL DC-MTL expand 300 1800000 3000
EXP-OTT DC-OTT expand 300 1400000 2500
{'first_year': 2027.0, 'years': 5.0, 'growth_per_year': 0.03, 'discount_rate': 0.08, 'weeks_per_year': 52.0, 'open_cost_new_site': 3000000.0, 'close_cost_existing_dc': 1500000.0}
one year, no growth: $4,809,623.52 = 52 x $92,492.76 a week (Day 23: $92,492.76)
The model reproduces Day 23 to the cent. Only now is it worth trusting with five years.
30.2 Doing nothing
# ---------- 30.2 Doing nothing ----------
existing = sites[sites.kind == "existing DC"]
for t in range(1, int(settings["years"]) + 1):
grown = stores.assign(pallets_per_week=stores.pallets_per_week * (1 + settings["growth_per_year"]) ** (t - 1))
d = build_location(existing, grown, lanes)
r = solver.solve(d, load_solutions=False)
ok = r.solver.termination_condition == pyo.TerminationCondition.optimal
print(f"{2026 + t}: {grown.pallets_per_week.sum():,.0f} pallets a week on 3,800 of capacity: "
f"{'fits' if ok else 'NO PLAN: some store cannot be served'}")
2027: 3,545 pallets a week on 3,800 of capacity: fits
2028: 3,651 pallets a week on 3,800 of capacity: fits
2029: 3,761 pallets a week on 3,800 of capacity: fits
2030: 3,874 pallets a week on 3,800 of capacity: NO PLAN: some store cannot be served
2031: 3,990 pallets a week on 3,800 of capacity: NO PLAN: some store cannot be served
By 2030, today's network can't serve every store: 3,874 pallets a week need more than 3,800 of capacity, and single sourcing needs some room to spare. Doing nothing is not an option; the question is what to do, and when.
30.3 The five-year plan
# ---------- 30.3 The five-year plan ----------
m = build_redesign(sites, stores, lanes, options, settings)
solver.solve(m)
plan = yearly_table(m, sites, options)
print(f"five-year cost, present value at the start of 2027: ${pyo.value(m.pv):,.2f}")
print(plan.to_string(index=False))
moves = sum(pyo.value(m.serve[i, j, t]) > 0.5 and pyo.value(m.serve[i, j, t - 1]) < 0.5
for i in m.I for j in m.J for t in m.T if t > 1)
print(f"stores that change DC from one year to the next: {moves}")
fig, axes = plt.subplots(1, 3, figsize=(13, 4))
for ax, i in zip(axes, ["DC-MIS", "DC-OTT", "DC-MTL"]):
years = [2026 + t for t in m.T]
load = [sum(m.demand[j, t] * pyo.value(m.serve[i, j, t]) for j in m.J) for t in m.T]
cap = [sites.capacity_pallets[i] + sum(options.extra_pallets[e] * pyo.value(m.built[e, t])
for e in m.E if options.site_id[e] == i) for t in m.T]
ax.bar(years, load, color="#4f7bd9", label="pallets a week")
ax.plot(years, cap, "--", color="#e08a2c", lw=2, label="capacity")
ax.set_title(f"{i} {sites.place[i]}")
ax.set_xticks(years)
ax.set_ylim(0, 1800)
axes[0].set_ylabel("pallets a week")
axes[0].legend(loc="lower left")
fig.suptitle("Five-year plan: load and capacity by DC")
fig.tight_layout()
fig.savefig("figures/day30_network_plan.png", dpi=110)
print("wrote figures/day30_network_plan.png")
five-year cost, present value at the start of 2027: $22,194,811.21
year pallets_a_week capacity sites expansions weekly_cost one_time
2027 3545 4100 MIS, MTL, OTT EXP-OTT 88694.71 1400000
2028 3651 4100 MIS, MTL, OTT EXP-OTT 89750.55 0
2029 3761 4100 MIS, MTL, OTT EXP-OTT 92711.44 0
2030 3874 4100 MIS, MTL, OTT EXP-OTT 94764.76 0
2031 3990 4100 MIS, MTL, OTT EXP-OTT 99847.25 0
stores that change DC from one year to the next: 9
wrote figures/day30_network_plan.png

- Expand Ottawa in 2027, and change nothing else. Present value of five years: $22.19 million.
- The expansion pays from the first year: the weekly cost falls from $92,492.76 to $88,694.71 including the expansion's $2,500 a week, because Ottawa-area stores no longer travel from Mississauga (the problem found on Day 14).
- No new site and no closure pays within five years at $3 million to open and $1.5 million to close.
- By 2031 the three DCs are almost full: the next decision is due around 2030 (see the scenarios).
- Nine store moves between DCs over the five years (as stores grow, the model re-balances). Each move costs effort the model doesn't see; Module 8 comes back to plan stability.
30.4 The gap report
# ---------- 30.4 Gap report ----------
for opts in ({}, {"mip_rel_gap": 0.01}):
h = run_highs(build_redesign(sites, stores, lanes, options, settings), **opts)
print(f"HiGHS {opts or 'defaults'}: {h['status']}, ${h['objective']:,.2f}, bound ${h['bound']:,.2f}, "
f"gap {h['gap_pct']:.3f}%, {h['nodes']} nodes")
HiGHS defaults: Optimal, $22,194,811.21, bound $22,194,811.21, gap 0.000%, 1 nodes
HiGHS {'mip_rel_gap': 0.01}: Optimal, $22,211,959.08, bound $22,052,924.17, gap 0.716%, 1 nodes
HiGHS proves the plan optimal (gap 0%). With a 1% gap, it stops sooner with a plan $17,148 more expensive (0.08%), and can only promise that no plan costs less than $22.05 million. For a five-year, $22 million decision, wait for the proof: it takes seconds here. On a bigger model (more years, more candidate sites, weekly instead of yearly periods) it may not, and then the report must say "this plan costs at most X% more than the best possible".
30.5 Scenarios
# ---------- 30.5 Scenarios ----------
rows = []
for name, kw in [("plan (growth 3%, rate 8%)", {}), ("growth 1%", {"growth": 0.01}), ("growth 5%", {"growth": 0.05}),
("discount rate 12%", {"rate": 0.12}), ("no Ottawa expansion", {"allowed_options": ["EXP-MTL", "EXP-MIS"]}),
("new sites free to open", {}), ]:
s = settings if name != "new sites free to open" else {**settings, "open_cost_new_site": 0}
m = build_redesign(sites, stores, lanes, options, s, **kw)
solver.solve(m)
t = yearly_table(m, sites, options)
first = {e: int(t.year[t.expansions.str.contains(e)].min()) for e in options.index if t.expansions.str.contains(e).any()}
rows.append((name, round(pyo.value(m.pv), 2), ", ".join(f"{e} {y}" for e, y in first.items()) or "-",
t.sites.iloc[-1]))
print(pd.DataFrame(rows, columns=["scenario", "present_value", "expansions", "sites_in_2031"]).to_string(index=False))
scenario present_value expansions sites_in_2031
plan (growth 3%, rate 8%) 22194811.21 EXP-OTT 2027 MIS, MTL, OTT
growth 1% 20996293.73 - MIS, MTL, OTT
growth 5% 23987941.78 EXP-MTL 2030, EXP-OTT 2027 MIS, MTL, OTT
discount rate 12% 20829515.86 EXP-OTT 2027 MIS, MTL, OTT
no Ottawa expansion 23026170.97 EXP-MTL 2029 MIS, MTL, OTT
new sites free to open 21661271.52 - MIS, MTL, OTT, QUE
- Growth decides the plan. At 1% a year, nothing needs building before 2031. At 5%, Ottawa in 2027 and Montreal in 2030.
- The discount rate doesn't: at 12% the plan is the same.
- Without the Ottawa expansion, the best plan expands Montreal in 2029 and costs $831,360 more over five years: Ottawa's expansion is worth that much.
- If new sites cost nothing to open, Quebec City opens. It is $3 million of one-time costs that keeps it out: a new DC needs a longer horizon than five years to pay.
30.6 The memo
A model memo
To: the Board. Re: the DC network, 2027–2031.
Recommendation. Expand the Ottawa DC by 300 pallets a week in 2027 ($1.4 million, then $2,500 a week). Keep the three DCs; open no new site in this period.
Why. At 3% growth a year, today's network can't serve every store by 2030. Expanding Ottawa solves that and lowers weekly costs at once, because Ottawa-area stores now served from Mississauga can be served locally: weekly costs fall by about $3,800 a week in 2027 after paying for the expansion. Five-year cost, present value: $22.2 million. Without the Ottawa expansion, the best alternative (expanding Montreal in 2029) costs $0.8 million more.
How sure. The plan is proven optimal for the stated costs and growth (gap 0%). It doesn't change with the discount rate (8% or 12%). It depends on growth: at 1% a year nothing is needed yet; at 5%, Montreal must also expand in 2030.
What to watch. By 2031 all three DCs are nearly full. We recommend reviewing the network in 2029 with actual growth, when a new site (Quebec City is the most promising: Days 23 and 30) or a Montreal expansion will be the next step.
Not in the model. Construction risk and timing within the year; the cost of moving stores between DCs (nine moves in five years); uncertainty in growth beyond the three scenarios (Module 6 treats it properly).
Module 3 wrap-up
| Day | Idea | Northbound decision |
|---|---|---|
| 21 | Binary variables, logic as constraints | Which bakery investments to buy |
| 22 | Fixed costs, big-M, minimum runs | Which products to make each week |
| 23 | Facility location | Is today's DC network right? |
| 24 | Knapsack, bin packing, cutting stock | Rush loads, trailers, cake bars |
| 25 | Integer trucks, location in a flow network | Which cross-docks to run |
| 26 | Branch and bound, cuts, gaps | How solvers prove a plan is best |
| 27 | Strong formulations, symmetry | Why some models solve and others don't |
| 28 | Measuring, sizing, solver choice | Christmas week loads |
| 29 | Piecewise costs, discounts | Overtime, flour contracts |
| 30 | Multi-year location | The five-year network plan |
Commit and tag
git add .
git commit -m "Day 30: capstone, five-year DC network plan"
git tag v3.0-module3
git push --tags
Then run the tests: tests/test_costs_and_plans.py checks Days 28–30 (the bound-sized packing, the discount models against each other, the all-units offer, and the capstone against Day 23). Add "day28", "day29", "day30" to the folders in conftest.py.
"""Module 3, Days 28-30: bound-sized packing, piecewise costs and the five-year network plan."""
import pyomo.environ as pyo
import pytest
from flour_costs import build_flour, load_flour
from highs_run import run_highs
from loads import fewest_trailers, lower_bound
from redesign import build_redesign, load_redesign
def test_fewest_trailers_monday(con):
week = con.sql("SELECT * FROM christmas_week_orders WHERE ship_date = '2026-12-21'").df().set_index("order_id")
trailers, proven, _, tries = fewest_trailers(week, 26, 16000, run_highs)
assert proven and tries == 1 and trailers == lower_bound(week, 26, 16000) == 16
def test_discount_models_agree_and_lp_bands_are_too_cheap(con):
flour, spec, bands, offer, delivery = load_flour(con)
cost = {}
for prices in ("list", "incremental", "piecewise", "bands_lp"):
m = build_flour(flour, spec, bands, prices=prices, need=55)
pyo.SolverFactory("highs").solve(m)
cost[prices] = pyo.value(m.cost)
assert cost["incremental"] == pytest.approx(cost["piecewise"], abs=0.01) == pytest.approx(25_038.64, abs=0.01)
assert cost["bands_lp"] < cost["incremental"] < cost["list"]
def test_all_units_offer_never_costs_more(con):
flour, spec, bands, offer, delivery = load_flour(con)
for need in (40, 55):
costs = []
for kw in ({}, {"offer": offer}):
m = build_flour(flour, spec, bands, prices="incremental", delivery=delivery, need=need, **kw)
pyo.SolverFactory("highs").solve(m)
costs.append(pyo.value(m.cost))
assert costs[1] <= costs[0] + 1e-6
def test_redesign_one_year_is_day23(con):
sites, stores, lanes, options, settings = load_redesign(con)
m = build_redesign(sites, stores, lanes, options, settings, years=1, growth=0)
pyo.SolverFactory("highs").solve(m)
assert pyo.value(m.pv) == pytest.approx(52 * 92_492.76, abs=0.05)
49 passed
Day 30 checklist
- I extended a single-period model to five years with timing logic (open once, close once, build once).
- I checked the multi-year model against a known single-year answer before using it.
- I showed that doing nothing fails, and when.
- I reported the plan with its present value and its gap.
- I tested the plan against growth, discount rate and unavailable options.
- I wrote a board memo with the recommendation, why, how sure, what to watch and what the model leaves out.