Prescriptive Analytics & Decision Intelligence
Overview / Module 3 / Day 25
Module 3 · Integer and Combinatorial Optimization · Day 25 of 80

Mini-project: Which Cross-Docks to Open

On Day 16 you sent chilled pallets through two cross-docks, Kingston and Trois-Rivières, and checked by hand whether each was worth its weekly cost. Transport now has six candidate sites and a complaint: "the model pays linehaul by the pallet, but we pay by the truck". Today is a full mini-project: rebuild the chilled network as a MIP with cross-docks to choose and whole trucks to pay for, and recommend which cross-docks to run.

▶
Video for Day 25 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:30
25.1 The brief, and today's network with whole trucks
0:30–1:45
25.2 Six candidates in one model
1:45–2:00
Break
2:00–2:45
25.3 Check: all 64 combinations
2:45–3:45
25.4–25.5 How close is each candidate? Scenarios
3:45–4:00
Break
4:00–4:45
25.6 The memo
4:45–5:00
Commit with Git + checklist

25.1 The brief

  • Network: Day 16's chilled network (two plants, three DCs, 40 stores, 922 pallets a week), with six candidate cross-docks (crossdock_candidates): Kingston and Trois-Rivières (running today), Cornwall, Belleville, Drummondville and Sherbrooke. Each has a weekly fixed cost and a throughput limit.
  • Arcs (crossdock_arcs): linehaul arcs from plants and DCs to each cross-dock, paid by the truck (26 pallets, $26×(2.50+0.08 km)\$26 \times (2.50 + 0.08\,\text{km}), so a full truck costs what Day 16 charged for 26 pallets), and delivery arcs from each cross-dock to stores within 260 km, paid by the pallet. Quebec stores need French labels, so only Quebec-side cross-docks and Cornwall may serve them.
  • Model: min-cost flow (Day 16) plus ox∈{0,1}o_x \in \{0,1\} for each cross-dock and na∈{0,1,2,… }n_a \in \{0, 1, 2, \dots\} trucks on each linehaul arc, with flowa≤26 na\text{flow}_a \le 26\, n_a. The plant-to-DC linehaul is paid by the truck too.

Create day25/crossdocks.py:

"""Day 25 mini-project: which cross-docks should the chilled network use?
Six candidate cross-docks, each with a weekly fixed cost; linehaul trucks paid by the truck, not by the pallet.

Import it:  from crossdocks import load_crossdock_network, build_crossdocks, report
"""
import pandas as pd
import pyomo.environ as pyo

TRUCK_PALLETS = 26


def load_crossdock_network(con):
    nodes = con.sql("SELECT * FROM chilled_nodes WHERE kind <> 'cross_dock'").df().set_index("node")
    stores = con.sql("SELECT store_id, province FROM stores").df().set_index("store_id")
    xds = con.sql("SELECT * FROM crossdock_candidates ORDER BY xd_id").df().set_index("xd_id")
    old = con.sql("""SELECT from_node, to_node, km, cost_per_pallet, capacity_pallets FROM chilled_arcs
                     WHERE from_node NOT LIKE 'XD-%' AND to_node NOT LIKE 'XD-%'""").df()
    old["arc_type"] = ["linehaul" if f.startswith("PL-") else "delivery" for f in old.from_node]
    old["cost_per_truck"] = (old.cost_per_pallet * TRUCK_PALLETS).where(old.arc_type == "linehaul")
    new = con.sql("SELECT * FROM crossdock_arcs").df()
    new["capacity_pallets"] = float("nan")
    arcs = pd.concat([old, new], ignore_index=True).set_index(["from_node", "to_node"])
    arcs["cost_per_pallet"] = arcs.cost_per_pallet.where(arcs.arc_type == "delivery",
                                                         arcs.cost_per_truck / TRUCK_PALLETS)
    return nodes, stores, xds, arcs


def build_crossdocks(nodes, xds, arcs, trucks=True, allowed=None, forced=(), cost_scale=1.0, demand_scale=1.0,
                     domain=pyo.Binary):
    """open[x] = 1 if cross-dock x runs this year. flow[a] = pallets a week on arc a.
    With trucks=True, every linehaul arc pays for whole trucks: trucks[a] >= flow[a] / 26."""
    m = pyo.ConcreteModel(name="crossdocks")
    m.X = pyo.Set(initialize=xds.index.tolist())
    m.A = pyo.Set(initialize=arcs.index.tolist(), dimen=2)
    m.L = pyo.Set(initialize=[a for a in arcs.index if arcs.arc_type[a] == "linehaul"], dimen=2)
    m.open = pyo.Var(m.X, within=domain)
    m.flow = pyo.Var(m.A, within=pyo.NonNegativeReals)
    for a in m.A:
        if not pd.isna(arcs.capacity_pallets[a]):
            m.flow[a].setub(float(arcs.capacity_pallets[a]))
    for x in m.X:
        if allowed is not None and x not in allowed:
            m.open[x].fix(0)
        if x in forced:
            m.open[x].fix(1)
    demand = {n: float(nodes.demand_pallets[n]) * demand_scale for n in nodes.index if nodes.kind[n] == "store"}
    inflow = {n: [a for a in arcs.index if a[1] == n] for n in list(nodes.index) + list(xds.index)}
    outflow = {n: [a for a in arcs.index if a[0] == n] for n in list(nodes.index) + list(xds.index)}

    def balance(m, n):
        net_in = sum(m.flow[a] for a in inflow[n]) - sum(m.flow[a] for a in outflow[n])
        if n in demand:
            return net_in == demand[n]
        if nodes.kind.get(n) == "plant":
            return -net_in <= float(nodes.throughput_capacity[n])
        return net_in == 0
    m.N = pyo.Set(initialize=list(nodes.index) + list(xds.index))
    m.balance = pyo.Constraint(m.N, rule=balance)
    dcs = [n for n in nodes.index if nodes.kind[n] == "dc"]
    m.dc_throughput = pyo.Constraint(dcs, rule=lambda m, n: sum(m.flow[a] for a in inflow[n]) <= float(nodes.throughput_capacity[n]))
    m.xd_throughput = pyo.Constraint(m.X, rule=lambda m, x: sum(m.flow[a] for a in inflow[x]) <= float(xds.throughput_pallets[x]) * m.open[x])
    # strong link: a store can only get pallets from an open cross-dock (at most all it needs)
    m.only_if_open = pyo.Constraint([a for a in arcs.index if a[0] in xds.index],
                                    rule=lambda m, x, s: m.flow[x, s] <= demand[s] * m.open[x])
    m.fixed = pyo.Expression(expr=sum(float(xds.fixed_cost_per_week[x]) * m.open[x] for x in m.X) + 0.0)
    m.delivery = pyo.Expression(expr=cost_scale * sum(float(arcs.cost_per_pallet[a]) * m.flow[a]
                                                      for a in m.A if a not in m.L))
    if trucks:
        m.trucks = pyo.Var(m.L, within=pyo.NonNegativeIntegers)
        m.full = pyo.Constraint(m.L, rule=lambda m, i, j: m.flow[i, j] <= TRUCK_PALLETS * m.trucks[i, j])
        m.linehaul = pyo.Expression(expr=cost_scale * sum(float(arcs.cost_per_truck[a]) * m.trucks[a] for a in m.L))
    else:
        m.linehaul = pyo.Expression(expr=cost_scale * sum(float(arcs.cost_per_pallet[a]) * m.flow[a] for a in m.L))
    m.cost = pyo.Objective(expr=m.fixed + m.linehaul + m.delivery)
    return m


def report(m, xds):
    """One line of costs, and the cross-docks used with the pallets through each."""
    used = [(x, round(sum(pyo.value(m.flow[a]) for a in m.A if a[1] == x), 1) + 0.0) for x in m.X if pyo.value(m.open[x]) > 0.5]
    text = ", ".join(f"{xds.place[x]} {p:g}" for x, p in used) or "none"
    return (f"${pyo.value(m.cost):,.2f} = fixed {pyo.value(m.fixed) + 0.0:,.0f} + linehaul {pyo.value(m.linehaul):,.2f} "
            f"+ delivery {pyo.value(m.delivery):,.2f}; cross-docks: {text}")

Three things to notice. trucks is a general integer variable, not a binary. The strong link from Day 23 (only_if_open: each store's delivery from a cross-dock is at most its demand times oxo_x) comes on top of the throughput row. And trucks=False gives back Day 16's per-pallet model, so you can check the new model against an answer you trust.

Then day25/run_crossdocks.py:

import itertools
import sys

import duckdb
import pandas as pd
import pyomo.environ as pyo

sys.path.insert(0, "day25")
from crossdocks import build_crossdocks, load_crossdock_network, report

pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
nodes, stores, xds, arcs = load_crossdock_network(con)
solver = pyo.SolverFactory("highs")


def solve(**kw):
    m = build_crossdocks(nodes, xds, arcs, **kw)
    solver.solve(m)
    return m


print(xds.to_string())
print(f"{len(arcs)} arcs: {(arcs.arc_type == 'linehaul').sum()} linehaul (paid by the truck), "
      f"{(arcs.arc_type == 'delivery').sum()} store deliveries (paid by the pallet)")

# ---------- 25.1 Today's network, two ways ----------
today = ("XD-KIN", "XD-TRV")
m = solve(trucks=False, allowed=today, forced=today)
print("today, per-pallet linehaul (Day 16):", report(m, xds))
m = solve(allowed=today, forced=today)
print("today, whole trucks:                ", report(m, xds))
for a in m.L:
    if pyo.value(m.trucks[a]) > 0.5:
        print(f"    {a[0]} -> {a[1]}: {pyo.value(m.flow[a]):.0f} pallets on {pyo.value(m.trucks[a]):.0f} truck(s)")
today_cost = pyo.value(m.cost)
                 place  fixed_cost_per_week  throughput_pallets
xd_id
XD-BEL      Belleville                  550                 140
XD-COR        Cornwall                  650                 180
XD-DRU   Drummondville                  700                 200
XD-KIN        Kingston                  500                 160
XD-SHE      Sherbrooke                  600                 120
XD-TRV  Trois-Rivieres                  900                 220
227 arcs: 19 linehaul (paid by the truck), 208 store deliveries (paid by the pallet)
today, per-pallet linehaul (Day 16): $19,603.64 = fixed 1,400 + linehaul 10,391.30 + delivery 7,812.34; cross-docks: Kingston 35, Trois-Rivieres 123
today, whole trucks:                 $19,993.74 = fixed 1,400 + linehaul 10,304.84 + delivery 8,288.90; cross-docks: Kingston 26, Trois-Rivieres 104
    PL-SHY -> DC-OTT: 200 pallets on 8 truck(s)
    PL-SHY -> DC-MTL: 283 pallets on 11 truck(s)
    PL-BRA -> DC-MIS: 335 pallets on 13 truck(s)
    DC-MIS -> XD-KIN: 26 pallets on 1 truck(s)
    PL-SHY -> XD-TRV: 104 pallets on 4 truck(s)

The first line is exactly Day 16's answer, $19,603.64: the new model is right before we change anything. Paying by the truck, the same network costs $19,993.74, $390 a week more, and the flows change: Kingston gets exactly 26 pallets (one full truck) instead of 35 (one and a third trucks), and Trois-Rivières 104 (four trucks) instead of 123. The per-pallet model sent partial trucks as if they were free.

25.2 Six candidates in one model

# ---------- 25.2 Six candidates ----------
m = solve(trucks=False)
print("best, per-pallet linehaul:", report(m, xds))
best = solve()
print("best, whole trucks:       ", report(best, xds))
print(f"saves ${today_cost - pyo.value(best.cost):,.2f} a week against today")
best, per-pallet linehaul: $18,445.14 = fixed 1,200 + linehaul 9,702.50 + delivery 7,542.64; cross-docks: Drummondville 123, Kingston 35
best, whole trucks:        $18,757.88 = fixed 700 + linehaul 9,027.20 + delivery 9,030.68; cross-docks: Drummondville 124
saves $1,235.86 a week against today
  • Per pallet, the model would open Drummondville and Kingston.
  • By the truck, it opens Drummondville only, for $18,757.88: $1,235.86 a week less than today (about $64,000 a year). Kingston's 26 to 35 pallets a week don't pay for a cross-dock once each truck must be paid in full.
  • Drummondville replaces Trois-Rivières: it is on the plant's route from Saint-Hyacinthe, cheaper to run ($700 against $900), and serves the three Quebec City and two Sherbrooke stores, straight from the plant at Saint-Hyacinthe.

25.3 Check: all 64 combinations

# ---------- 25.3 Check by trying all 64 combinations ----------
results = []
for keep in itertools.product([0, 1], repeat=len(xds)):
    chosen = tuple(x for x, k in zip(xds.index, keep) if k)
    m = solve(allowed=chosen, forced=chosen)
    results.append((pyo.value(m.cost), ", ".join(c[3:] for c in chosen) or "none"))
results.sort()
print("best five of 64:", "; ".join(f"{c} ${v:,.2f}" for v, c in results[:5]))
best five of 64: DRU $18,757.88; DRU, KIN $18,842.95; BEL, DRU $18,989.67; COR, DRU $19,173.46; DRU, SHE $19,186.06

Sixty-four solves, the same best answer as one MIP. Note how close the runners-up are: adding Kingston costs only $85 a week more.

25.4 How close is each candidate?

# ---------- 25.4 Force each candidate open ----------
rows = []
for x in xds.index:
    m = solve(forced=(x,))
    extra = pyo.value(m.cost) - pyo.value(best.cost)
    used = ", ".join(y[3:] for y in m.X if pyo.value(m.open[y]) > 0.5)
    rows.append((x, xds.place[x], xds.fixed_cost_per_week[x], round(extra, 2) + 0.0, used))
print(pd.DataFrame(rows, columns=["forced", "place", "fixed_cost", "extra_cost", "open"]).to_string(index=False))
forced          place  fixed_cost  extra_cost     open
XD-BEL     Belleville         550      231.79 BEL, DRU
XD-COR       Cornwall         650      415.58 COR, DRU
XD-DRU  Drummondville         700        0.00      DRU
XD-KIN       Kingston         500       85.07 DRU, KIN
XD-SHE     Sherbrooke         600      428.18 DRU, SHE
XD-TRV Trois-Rivieres         900      882.20 SHE, TRV

Kingston is $85 a week from paying; Trois-Rivières, today's biggest cross-dock, is $882 a week from paying. Forced open, Trois-Rivières drags Sherbrooke in with it, not Drummondville.

25.5 Scenarios

# ---------- 25.5 Scenarios ----------
for name, kw in [("fuel and wages +30%", dict(cost_scale=1.3)), ("chilled demand +15%", dict(demand_scale=1.15)),
                 ("both", dict(cost_scale=1.3, demand_scale=1.15)), ("no cross-docks at all", dict(allowed=()))]:
    print(f"{name:<22}", report(solve(**kw), xds))
fuel and wages +30%    $24,135.83 = fixed 1,200 + linehaul 12,625.65 + delivery 10,310.18; cross-docks: Drummondville 124, Kingston 26
chilled demand +15%    $21,760.11 = fixed 700 + linehaul 9,383.40 + delivery 11,676.71; cross-docks: Drummondville 150.3
both                   $28,038.70 = fixed 1,200 + linehaul 13,088.71 + delivery 13,749.99; cross-docks: Drummondville 150.3, Kingston 26
no cross-docks at all  $20,194.89 = fixed 0 + linehaul 9,079.20 + delivery 11,115.69; cross-docks: none
  • Drummondville is in every scenario. It is a robust choice.
  • Kingston comes back if transport costs rise 30% (fuel and drivers' wages), because longer direct runs cost more. With 15% more demand alone, it stays closed.
  • No cross-docks at all costs $20,194.89: cross-docks are worth $1,437 a week, and almost all of that comes from Drummondville.

25.6 The memo

A model memo

To: Director of Transport. Re: chilled cross-docks.

"We recommend running one chilled cross-dock, in Drummondville, instead of the two in Kingston and Trois-Rivières. The model saves $1,236 a week ($64,000 a year) before one-time costs, mainly by moving Quebec stores' chilled pallets through a cheaper site on the plant's route.

Kingston is a close call: it costs $85 a week more than it saves at today's prices, and becomes worth keeping if transport costs rise by 30%. We suggest keeping the Kingston lease on a short renewal rather than closing it at once.

Trois-Rivières costs $882 a week more than it saves; close it once Drummondville runs.

Our earlier analysis (Day 16) paid linehaul by the pallet and overstated the value of small flows. This study pays for whole trucks, as transport does."

Commit

git add .
git commit -m "Day 25: cross-dock location with whole trucks"
git push

Day 25 checklist

  • I extended a min-cost flow with yes/no sites and integer trucks.
  • I checked the new model reproduces an answer I trust (Day 16) before using it.
  • I can explain why paying by the truck changes the answer.
  • I checked one MIP against all 64 combinations.
  • I tested the answer under scenarios and found which choices are robust.
  • I wrote a recommendation with the close calls flagged.