Set-up
Install OR-Tools in your virtual environment (it is in requirements.txt from today):
pip install ortools==9.15.6755
Copy the latest make_data.py from the Course data page and rebuild (python make_data.py, python day01/ladder.py, python day06/load_tables.py). New for Days 31–33: the Montreal DC's warehouse staff (dc_staff), shifts (dc_shifts), people needed per shift (dc_coverage), labour rules (dc_rules), who worked last Sunday (dc_last_sunday), the supervisor's roster for next week (dc_current_roster) and staff requests (staff_requests).
31.1 Domains and a global constraint
Day 14's eight drivers and eight routes, written the CP way. Instead of 64 yes/no variables, one integer variable per driver: which route (0 to 7). One global constraint, AllDifferent, says no two drivers share a route. An element constraint looks up each driver's minutes on the chosen route. Create day31/first_models.py:
import duckdb
from ortools.sat.python import cp_model
con = duckdb.connect("northbound.duckdb", read_only=True)
rows = con.sql("SELECT driver, route, minutes FROM driver_route_minutes ORDER BY driver, route").fetchall()
drivers = sorted({d for d, _, _ in rows})
routes = sorted({r for _, r, _ in rows})
minutes = {(d, r): int(t) for d, r, t in rows}
def solver(workers=8):
s = cp_model.CpSolver()
s.parameters.num_workers = workers
s.parameters.interleave_search = True # deterministic: the same answer on every run
s.parameters.max_time_in_seconds = 60
return s
# ---------- 31.1 Variables with domains, a global constraint ----------
m = cp_model.CpModel()
route_of = {d: m.new_int_var(0, len(routes) - 1, f"route_of_{d}") for d in drivers} # which route each driver takes
m.add_all_different(route_of.values()) # no two drivers on one route
time_of = {d: m.new_int_var(0, 1000, f"minutes_{d}") for d in drivers}
for d in drivers:
m.add_element(route_of[d], [minutes[d, r] for r in routes], time_of[d]) # time_of[d] = minutes[d][route_of[d]]
m.minimize(sum(time_of.values()))
s = solver()
print(s.status_name(s.solve(m)), f"{s.objective_value:,.0f} minutes:", {d: routes[s.value(route_of[d])] for d in drivers})
OPTIMAL 2,768 minutes: {'D1': 'R3', 'D2': 'R1', 'D3': 'R5', 'D4': 'R7', 'D5': 'R6', 'D6': 'R2', 'D7': 'R4', 'D8': 'R8'}
The same 2,768 minutes as Day 14. Three things are different from a MIP:
- Only whole numbers. CP-SAT's variables and coefficients are integers. Costs in dollars and cents must be scaled (31.4).
- Global constraints (
AllDifferent,Element,Circuit,NoOverlap,Cumulative…) carry meaning the solver exploits directly. - Search, not only relaxations. CP-SAT propagates each decision through the constraints, learns from dead ends (as SAT solvers do), and runs several strategies in parallel (
num_workers). Withinterleave_search=Truethe parallel search is deterministic: the same answer on every run. (On another computer or operating system an equally good plan may come out, with the same cost: when plans tie, any of them is a correct answer.)
31.2 Business rules as logic
Real driver rules from the Montreal depot:
- D8 is new: not R8, which crosses the busy port area.
- D2 and D7 share a car: both start from the same yard (R3, R4, R7 and R8 leave from the south yard).
- At most one of the three senior drivers (D1, D4, D7) in the south yard.
- Nobody over 390 minutes (Day 14).
# ---------- 31.2 Business rules as logic ----------
take = {(d, r): m.new_bool_var(f"{d}_{r}") for d in drivers for r in routes} # take[d, r] <=> route_of[d] == r
for d in drivers:
for k, r in enumerate(routes):
m.add(route_of[d] == k).only_enforce_if(take[d, r])
m.add(route_of[d] != k).only_enforce_if(take[d, r].Not())
south = {d: m.new_bool_var(f"south_{d}") for d in drivers} # R3, R4, R7, R8 leave from the south yard
for d in drivers:
m.add(sum(take[d, r] for r in ("R3", "R4", "R7", "R8")) == 1).only_enforce_if(south[d])
m.add(sum(take[d, r] for r in ("R3", "R4", "R7", "R8")) == 0).only_enforce_if(south[d].Not())
m.add(take["D8", "R8"] == 0) # D8 is new: R8 crosses the busy port area
m.add(south["D2"] == south["D7"]) # D2 and D7 share a car: same yard
m.add(sum(south[d] for d in ("D1", "D4", "D7")) <= 1) # at most one of the three senior drivers in the south yard
for d in drivers:
m.add(time_of[d] <= 390) # nobody over 6.5 hours (Day 14)
s = solver()
print(s.status_name(s.solve(m)), f"{s.objective_value:,.0f} minutes with the rules:",
{d: routes[s.value(route_of[d])] for d in drivers})
OPTIMAL 2,844 minutes with the rules: {'D1': 'R3', 'D2': 'R1', 'D3': 'R8', 'D4': 'R5', 'D5': 'R6', 'D6': 'R4', 'D7': 'R2', 'D8': 'R7'}
only_enforce_if attaches a constraint to a yes/no variable: take[d, r] is linked to route_of[d] in both directions, and south[d] to the four south-yard routes. The rules cost 76 minutes a day (2,844 against 2,768). In a MIP, "share a car" and "same yard" need extra binaries and big-M rows; here each is one line.
31.3 Other objectives; counting solutions
# ---------- 31.3 Other objectives: the longest route, and how many best answers ----------
longest = m.new_int_var(0, 1000, "longest")
m.add_max_equality(longest, list(time_of.values()))
m.minimize(longest)
s = solver()
s.solve(m)
best_longest = int(s.objective_value)
print(f"shortest possible longest route: {best_longest} minutes")
m.add(longest <= best_longest)
m.minimize(sum(time_of.values())) # then the least total time among those
s = solver()
s.solve(m)
best_total = int(s.objective_value)
print(f"least total with nobody over {best_longest}: {best_total:,} minutes")
class Count(cp_model.CpSolverSolutionCallback):
def __init__(self):
super().__init__()
self.n = 0
def on_solution_callback(self):
self.n += 1
m.clear_objective()
m.add(sum(time_of.values()) <= best_total)
s = cp_model.CpSolver()
s.parameters.enumerate_all_solutions = True
counter = Count()
s.solve(m, counter)
print(f"assignments that reach both: {counter.n}")
shortest possible longest route: 387 minutes
least total with nobody over 387: 2,844 minutes
assignments that reach both: 1
- Minimize the longest route:
add_max_equalitybuilds the maximum directly. 387 minutes is the floor (nobody drives R3 faster), and the plan from 31.2 already reaches it. - Lexicographic objectives: fix the first objective's best value as a constraint, then optimize the second.
- Counting solutions: with
enumerate_all_solutionsand a callback, CP-SAT lists every solution of a model without an objective. Only one assignment reaches both 387 and 2,844: the planners have no alternatives to choose from. When several plans tie, counting them tells you how much freedom is left for other wishes (Day 33).
Decision it supports: assignments with many logical rules (who may do what, who goes with whom).
Other decisions you can support the same way: exam timetables · seating plans · matching volunteers to tasks · sports schedules.
31.4 CP-SAT or MIP?
The Christmas trailers again (Days 26–28), as a CP-SAT model:
# ---------- 31.4 CP-SAT on the Christmas trailers (Day 27) ----------
orders = con.sql("SELECT * FROM christmas_orders ORDER BY order_id").df().set_index("order_id")
for n in (16, 15):
b = cp_model.CpModel()
put = {(o, k): b.new_bool_var(f"put_{o}_{k}") for o in orders.index for k in range(n)}
use = [b.new_bool_var(f"use_{k}") for k in range(n)]
for o in orders.index:
b.add_exactly_one(put[o, k] for k in range(n))
for k in range(n):
b.add(sum(int(orders.pallets[o]) * put[o, k] for o in orders.index) <= 26 * use[k])
b.add(sum(int(orders.weight_kg[o]) * put[o, k] for o in orders.index) <= 16000 * use[k])
b.minimize(sum(use))
s = solver()
status = s.solve(b)
print(f"Christmas, {n} trailers allowed: {s.status_name(status)}, {s.objective_value:.0f} trailers, "
f"bound {s.best_objective_bound:.0f}")
Christmas, 16 trailers allowed: OPTIMAL, 15 trailers, bound 15
Christmas, 15 trailers allowed: OPTIMAL, 15 trailers, bound 15
CP-SAT proves 15 trailers in a few seconds with either model (16 or 15 trailers allowed), where HiGHS needed up to 16,000 nodes on some seeds (Day 28). A rough guide:
| Use CP-SAT when | Use a MIP solver when |
|---|---|
| Decisions are yes/no or small integers | There are many continuous variables (flows, amounts) |
| Rules are logical: if-then, all-different, sequences, no overlap | Costs and limits are mostly linear |
| Time is in whole units (minutes, shifts) | The LP relaxation is tight (Days 23, 27) |
| Finding any feasible plan is the hard part | You need duals and ranging (Module 2) |
Both are worth trying on a new problem: measure, as on Day 28.
The planted bug
day31/bug_rounding.py solves Day 15's assignment in CP-SAT: "it wants integers, so int() the costs". Run it.
con = duckdb.connect("northbound.duckdb", read_only=True)
dcs, stores, lanes = load_network(con)
lanes = lanes.assign(cost_per_pallet=lanes.cost_per_pallet.astype(int)) # whole dollars a pallet
m, assign = build_cp_assignment(dcs, stores, lanes, to_int=int)
status, value, _, plan = solve_and_price(m, assign, lanes, stores)
print(f"{status}: ${value:,.0f} a week")
real = load_network(con)[2]
print(f"the same plan at the real lane costs: ${sum(real.cost_per_pallet[d, s] * stores.pallets_per_week[s] for s, d in plan.items()):,.2f}")
What happens, and why
OPTIMAL: $39,395 a week
the same plan at the real lane costs: $41,492.76
int() truncates: $4.39 a pallet becomes $4, $60.34 becomes $60. The model reports $39,395 a week, $2,098 less than the plan really costs. Here the plan happens to be the same; with closer costs, truncation changes which plan wins too. Scale to the precision you need (cents: multiply by 100, then round), say so in the code, and price the final plan at the real costs as a check.
Mini-project: Day 15's assignment in CP-SAT
Write Day 15's single-sourcing model (each store to exactly one DC, DC capacities, French labels, six hours on the road) in CP-SAT with costs in cents, and check it against HiGHS.
Solution
"""Day 31: Day 15's store-to-DC assignment written for CP-SAT, which only knows whole numbers.
Import it: from cp_assignment import build_cp_assignment
"""
from ortools.sat.python import cp_model
MAX_MINUTES = 360
def build_cp_assignment(dcs, stores, lanes, to_int=lambda dollars: round(100 * dollars)):
"""assign[d, s] = 1 if DC d serves store s. Costs become whole numbers with to_int (default: cents)."""
m = cp_model.CpModel()
assign = {}
for d in dcs.index:
for s in stores.index:
french_rule = stores.province[s] == "QC" and not dcs.ships_french_labels[d]
if not french_rule and lanes.minutes[d, s] <= MAX_MINUTES:
assign[d, s] = m.new_bool_var(f"assign_{d}_{s}")
for s in stores.index:
m.add_exactly_one(assign[d, s] for d in dcs.index if (d, s) in assign)
for d in dcs.index:
m.add(sum(int(stores.pallets_per_week[s]) * assign[d, s] for s in stores.index if (d, s) in assign)
<= int(dcs.pallets_per_week_capacity[d]))
m.minimize(sum(to_int(lanes.cost_per_pallet[d, s] * stores.pallets_per_week[s]) * x for (d, s), x in assign.items()))
return m, assign
def solve_and_price(m, assign, lanes, stores):
"""Solve, then price the plan at the real (decimal) lane costs."""
s = cp_model.CpSolver()
s.parameters.num_workers = 8
s.parameters.interleave_search = True
status = s.solve(m)
chosen = [(d, st) for (d, st), x in assign.items() if s.value(x)]
real = sum(lanes.cost_per_pallet[d, st] * stores.pallets_per_week[st] for d, st in chosen)
return s.status_name(status), s.objective_value, round(real, 2), dict((st, d) for d, st in chosen)
"""Day 31 mini-project: Day 15's single-sourcing assignment with CP-SAT. Same answer as the MIP?
Run from the repository root (after day06/load_tables.py): python day31/mini_project_assignment.py
"""
import sys
import duckdb
import pyomo.environ as pyo
for folder in ("day14", "day15", "day31"):
sys.path.insert(0, folder)
from cp_assignment import build_cp_assignment, solve_and_price
from store_assignment import build_assignment
from transport import load_network
con = duckdb.connect("northbound.duckdb", read_only=True)
dcs, stores, lanes = load_network(con)
m, assign = build_cp_assignment(dcs, stores, lanes)
status, cents, real, plan = solve_and_price(m, assign, lanes, stores)
print(f"CP-SAT: {status}, objective {cents:,.0f} cents = ${real:,.2f} a week")
mip = build_assignment(dcs, stores, lanes)
pyo.SolverFactory("highs").solve(mip)
mip_plan = {s: d for d in mip.D for s in mip.S if pyo.value(mip.assign[d, s]) > 0.5}
print(f"HiGHS (Day 15): ${pyo.value(mip.cost):,.2f} a week")
print("stores assigned differently:", sorted(s for s in plan if plan[s] != mip_plan[s]) or "none")
CP-SAT: OPTIMAL, objective 4,149,276 cents = $41,492.76 a week
HiGHS (Day 15): $41,492.76 a week
stores assigned differently: none
The same plan and the same cost to the cent: 4,149,276 cents = $41,492.76. add_exactly_one is CP-SAT's "one of these is 1". Two solvers agreeing is a strong check on both models.
Commit
git add .
git commit -m "Day 31: CP-SAT"
git push
Day 31 checklist
- I can write a CP-SAT model with integer domains,
AllDifferentandElement. - I can attach constraints to yes/no variables with
only_enforce_if. - I can minimize a maximum and solve objectives in order.
- I can count solutions with a callback.
- I scale money to cents, round (not truncate), and price the final plan at real costs.
- I can say when I'd try CP-SAT before a MIP solver.