Prescriptive Analytics & Decision Intelligence
Overview / Module 2 / Day 15
Module 2 · Sensitivity, Duality and Network Flows · Day 15 of 80

Mini-project: Assigning Stores to DCs

Day 14's plan split two stores between two DCs. Store managers hate that: two delivery schedules, two sets of paperwork, two trucks at the dock. Northbound's rule is single sourcing: each store gets everything from one DC. Today you build that plan with the business rules, compare it with today's routing and with Day 14's split plan, and price an expansion of the Ottawa DC.

▶
Video for Day 15 coming soon

In this lesson

Today's 5-hour plan

LessonProjectBreakCommit
0:00–0:30
15.1 The brief
0:30–1:45
15.2 One DC per store, with binary variables
1:45–2:00
Break
2:00–2:45
15.3 Which rules bind?
2:45–3:45
15.4 What is a bigger Ottawa DC worth?
3:45–4:00
Break
4:00–4:45
15.5 The map and the memo
4:45–5:00
Commit with Git + checklist

15.1 The brief

From: VP Logistics

Ottawa is 223 pallets a week over capacity, and I want a store-to-DC map that fits. Rules: every store is served by exactly one DC; Quebec stores need French-labelled stock, which Mississauga doesn't carry; fresh products may spend at most six hours on a truck. Tell me what the map costs, which stores move, and what it would be worth to expand Ottawa by 100, 200 or 300 pallets a week.

15.2 One DC per store, with binary variables

"Exactly one DC" is a yes/no decision per store and DC: binary variables, ad,s∈{0,1}a_{d,s} \in \{0, 1\}. The pallets shipped are then demands×ad,s\text{demand}_s \times a_{d,s}:

min⁡∑d,scostd,s demands ad,ss.t.∑dad,s=1∀s∑sdemands ad,s≤capacityd∀dad,s=0for lanes over 6 hours, and Mississauga to Quebec storesad,s∈{0,1}\begin{aligned} \min\quad & \sum_{d,s} \text{cost}_{d,s}\, \text{demand}_s\, a_{d,s} \\ \text{s.t.}\quad & \textstyle\sum_d a_{d,s} = 1 && \forall s \\ & \textstyle\sum_s \text{demand}_s\, a_{d,s} \le \text{capacity}_d && \forall d \\ & a_{d,s} = 0 && \text{for lanes over 6 hours, and Mississauga to Quebec stores} \\ & a_{d,s} \in \{0, 1\} \end{aligned}

This model does not have Day 14's special structure: the capacity rows weigh each store by its pallets. Without the binary requirement, the solver would happily split stores again. With within=pyo.Binary, HiGHS solves a mixed-integer program (MIP). How it does that (branch and bound) is Module 3; today we use it. Create day15/store_assignment.py:

import os
import sys

import duckdb
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
import pyomo.environ as pyo

sys.path.insert(0, "day14")
from transport import build_transport, load_network

pd.set_option("display.width", 140)
MAX_MINUTES = 360          # fresh products: at most six hours on the truck


def build_assignment(dcs, stores, lanes, capacity=None):
    """Single sourcing: assign[d, s] = 1 if DC d serves all of store s. A binary variable (Module 3 explains how
    the solver handles it; today we just use it)."""
    capacity = capacity or dcs.pallets_per_week_capacity.to_dict()
    m = pyo.ConcreteModel(name="store_assignment")
    m.D = pyo.Set(initialize=dcs.index.tolist())
    m.S = pyo.Set(initialize=stores.index.tolist())
    m.assign = pyo.Var(m.D, m.S, within=pyo.Binary)
    m.one_dc = pyo.Constraint(m.S, rule=lambda m, s: sum(m.assign[d, s] for d in m.D) == 1)
    m.capacity = pyo.Constraint(m.D, rule=lambda m, d: sum(stores.pallets_per_week[s] * m.assign[d, s] for s in m.S) <= capacity[d])
    for d in m.D:
        for s in m.S:
            french_rule = stores.province[s] == "QC" and not dcs.ships_french_labels[d]
            too_far = lanes.minutes[d, s] > MAX_MINUTES
            if french_rule or too_far:
                m.assign[d, s].fix(0)
    m.cost = pyo.Objective(expr=sum(lanes.cost_per_pallet[d, s] * stores.pallets_per_week[s] * m.assign[d, s]
                                    for d in m.D for s in m.S))
    return m


def chosen_dc(m):
    return {s: next(d for d in m.D if pyo.value(m.assign[d, s]) > 0.5) for s in m.S}

Forbidden lanes are handled by fixing their variables to 0 (fix(0)), as in the drivers mini-project. And the script:

if __name__ == "__main__":
    con = duckdb.connect("northbound.duckdb")
    dcs, stores, lanes = load_network(con)
    solver = pyo.SolverFactory("highs")

    # ---------- 15.1 Three answers to compare ----------
    today = sum(lanes.cost_per_pallet[stores.current_dc[s], s] * stores.pallets_per_week[s] for s in stores.index)
    lp = build_transport(dcs, stores, lanes)
    solver.solve(lp)
    m = build_assignment(dcs, stores, lanes)
    solver.solve(m)
    print(f"today (Ottawa over capacity):     ${today:,.2f}")
    print(f"pallets split freely (Day 14):    ${pyo.value(lp.cost):,.2f}")
    print(f"one DC per store, all rules:      ${pyo.value(m.cost):,.2f}")

    plan = pd.DataFrame({"city": stores.city, "pallets": stores.pallets_per_week,
                         "today": stores.current_dc, "new": pd.Series(chosen_dc(m))})
    plan["new_cost"] = [lanes.cost_per_pallet[plan.new[s], s] * plan.pallets[s] for s in plan.index]
    print(plan.groupby("new").pallets.sum().to_frame("pallets").join(dcs.pallets_per_week_capacity).to_string())
    print("Stores that change DC:")
    print(plan[plan.today != plan.new].to_string())
today (Ottawa over capacity):     $35,194.71
pallets split freely (Day 14):    $39,089.81
one DC per store, all rules:      $41,492.76
        pallets  pallets_per_week_capacity
new
DC-MIS     1365                       1600
DC-MTL     1480                       1500
DC-OTT      700                        700
Stores that change DC:
         city  pallets   today     new  new_cost
S20    Ottawa       87  DC-OTT  DC-MIS   4584.90
S23  Kingston       83  DC-OTT  DC-MIS   3120.80
S24  Gatineau       53  DC-OTT  DC-MTL   1482.94

Three plans, three costs:

PlanWeekly costFeasible?
Today's routing$35,194.71No: Ottawa 223 pallets over
Pallets split freely (Day 14)$39,089.81Yes, but two stores split
One DC per store, all rules$41,492.76Yes

Single sourcing costs $2,402.95 a week more than splitting. The reason is visible in the moves: to get Ottawa under 700 pallets, a whole Ottawa store (S20, 87 pallets) must go to Mississauga, 438 km away, at $4,584.90 a week for that one store. When the model could split, it moved only the pallets it needed to.

15.3 Which rules bind?

    # ---------- 15.2 Which rules bind? ----------
    excluded_far = [(d, s) for d in dcs.index for s in stores.index if lanes.minutes[d, s] > MAX_MINUTES]
    print(f"lanes over {MAX_MINUTES} minutes: {len(excluded_far)} of {len(lanes)}")
    m_free = build_assignment(dcs, stores, lanes)
    for v in m_free.assign.values():
        v.unfix()
    solver.solve(m_free)
    print(f"without the French-label and time rules: ${pyo.value(m_free.cost):,.2f}")
lanes over 360 minutes: 38 of 120
without the French-label and time rules: $41,492.76

38 of 120 lanes are too long for fresh products, and Mississauga can't serve Quebec. Yet removing both rules leaves the cost unchanged: neither rule binds. The cheap lanes are short, and Mississauga is never the cheapest DC for a Quebec store anyway. That's worth saying in the memo: the rules cost nothing today, so nobody needs to argue about them.

15.4 What is a bigger Ottawa DC worth?

    # ---------- 15.3 What-if: Ottawa DC grows to 900 pallets ----------
    for ott in (700, 800, 900, 1000):
        cap = dict(dcs.pallets_per_week_capacity, **{"DC-OTT": ott})
        mm = build_assignment(dcs, stores, lanes, cap)
        solver.solve(mm)
        print(f"  Ottawa {ott:>4} pallets: ${pyo.value(mm.cost):,.2f}  (saves ${pyo.value(m.cost) - pyo.value(mm.cost):,.2f} a week)")
  Ottawa  700 pallets: $41,492.76  (saves $0.00 a week)
  Ottawa  800 pallets: $36,696.10  (saves $4,796.66 a week)
  Ottawa  900 pallets: $35,755.71  (saves $5,737.05 a week)
  Ottawa 1000 pallets: $35,194.71  (saves $6,298.05 a week)

A 100-pallet expansion saves $4,796.66 a week, nearly $250,000 a year. The second 100 pallets add only $940; the third $561. At 1,000 pallets the plan returns to today's routing: today's map is what a big enough Ottawa DC would choose.

This is Day 13's diminishing returns again, but sharper: the first 100 pallets let the model bring the Ottawa store S20 home from Mississauga, which is worth far more than any later pallet. Single sourcing makes the value of capacity lumpy: it jumps when one more whole store fits.

Try it 15.1

With the free-split model from Day 14, what would 100 more pallets in Ottawa save? Why is it less than $4,796.66?

Solution
lp = build_transport(dcs, stores, lanes, dict(dcs.pallets_per_week_capacity, **{"DC-OTT": 800}))
pyo.SolverFactory("highs").solve(lp)
print(39_089.81 - pyo.value(lp.cost))

It saves $2,525.60 a week. Ottawa's shadow price ($48.18 a pallet) would predict $4,818, but it holds for only part of the 100 pallets (Day 12). And the single-sourcing plan starts from a worse position ($41,492.76), so it has more to gain: there, the expansion also undoes the expensive S20 move.

15.5 The map and the memo

    # ---------- 15.4 Store and draw the assignment ----------
    con.sql("CREATE OR REPLACE TABLE store_dc_assignment AS SELECT * FROM plan")
    places = con.sql("SELECT store_id, latitude, longitude FROM store_logistics").df().set_index("store_id")
    dc_loc = con.sql("SELECT d.dc_id, p.latitude, p.longitude FROM dc_logistics d JOIN places p ON p.place = d.city").df().set_index("dc_id")
    colours = {"DC-MIS": "#4f7bd9", "DC-OTT": "#e08a2c", "DC-MTL": "#3ea86b"}
    os.makedirs("figures", exist_ok=True)
    fig, ax = plt.subplots(figsize=(10, 5.5))
    for s, row in plan.iterrows():
        d = row.new
        ax.plot([dc_loc.longitude[d], places.longitude[s]], [dc_loc.latitude[d], places.latitude[s]],
                color=colours[d], lw=0.8, alpha=0.7, ls="-" if d == row.today else "--")
        ax.scatter(places.longitude[s], places.latitude[s], s=row.pallets / 2, color=colours[d], zorder=3)
    for d, row in dc_loc.iterrows():
        ax.scatter(row.longitude, row.latitude, marker="s", s=160, color=colours[d], edgecolor="black", zorder=4, label=d)
    ax.set_title("Store-to-DC assignment (dashed = store changes DC; dot size = pallets a week)")
    ax.set_xlabel("longitude")
    ax.set_ylabel("latitude")
    ax.legend()
    fig.tight_layout()
    fig.savefig("figures/day15_assignment.png", dpi=120)
    print("saved figures/day15_assignment.png")
    con.close()

Store to DC assignment

The assignment is stored in store_dc_assignment for the next days, and drawn: solid lines are stores that keep their DC, dashed lines stores that change.

Write day15/memo.md for the VP.

Model answer

To: VP Logistics Re: A store-to-DC map that fits

Recommendation. Move three stores: Ottawa S20 and Kingston S23 to Mississauga, Gatineau S24 to Montreal. Every store keeps a single DC, and Ottawa ships exactly its 700 pallets. Weekly shipping cost: $41,492.76, against $35,194.71 for today's map, which only works through Ottawa's overtime and trailer yard.

The rules cost nothing. French labelling and the six-hour limit don't change the plan: the cheapest DC for every store already meets them.

Expand Ottawa by 100 pallets. It saves $4,797 a week (about $249,000 a year) by bringing S20 home. A second 100 pallets adds only $940 a week, a third $561. If a 100-pallet expansion costs less than about $4,800 a week to run, do it; then compare its full cost with today's overtime.

Caveat. Lane costs are averages per pallet; a real delivery schedule groups stores into truck routes (Module 4).

Commit

git add .
git commit -m "Day 15: single-sourcing store assignment, Ottawa expansion"
git push

Day 15 checklist

  • I can model single sourcing with binary variables and solve it with HiGHS.
  • I compared today's routing, a split plan and a single-sourcing plan, and explained the differences.
  • I checked which business rules bind, and reported the ones that don't.
  • I priced capacity in steps and saw that single sourcing makes its value lumpy.
  • I stored the assignment in the database and drew it on a map.
  • My memo gives the VP a decision, its cost and its value.