Update the course data
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 34–37: bakery_machines, bakery_night_jobs, bakery_operations and bakery_rules (tonight's run, Day 34), forklift_certification (Day 35), delivery_stops, delivery_matrix and delivery_fleet (tomorrow morning's bread run, Days 36–37).
34.1 The data and the head baker's plan
Times are minutes after 21:00. Bread and viennoiserie must be packed by 04:00, when the delivery vans load (Days 36–37); cakes and cookies by 05:00 or 06:00. Create day34/bakery_shop.py:
"""Day 34: tonight's bakery run as a job shop, with CP-SAT interval variables.
Import it: from bakery_shop import load_shop, build_schedule, solve_schedule, dispatch_fifo, check_schedule, clock
"""
import pandas as pd
from ortools.sat.python import cp_model
HORIZON = 900 # minutes after 21:00
def clock(minute, start=1260):
t = (start + int(minute)) % 1440
return f"{t // 60:02d}:{t % 60:02d}"
def load_shop(con):
jobs = con.sql("SELECT * FROM bakery_night_jobs ORDER BY job_id").df().set_index("job_id")
ops = con.sql("SELECT * FROM bakery_operations ORDER BY job_id, step").df()
machines = con.sql("SELECT * FROM bakery_machines").df().set_index("machine_id")
rules = dict(con.sql("SELECT * FROM bakery_rules").fetchall())
return jobs, ops, machines, rules
def build_schedule(jobs, ops, machines, rules, one_of_each=False, proofer_limit=True, max_wait=True,
objective="makespan", oven_down=None):
"""start/end of every operation. one_of_each: only MIX-1 and OVEN-1 work (a short-staffed night).
objective: "makespan" (finish everything as early as possible) or "lateness" (total minutes late, then makespan).
oven_down: (from, to) minutes when OVEN-2 is out of service."""
m = cp_model.CpModel()
start, end, choice = {}, {}, {}
on_machine = {mid: [] for mid in machines.index}
proofer = []
for r in ops.itertuples():
key = (r.job_id, r.step)
start[key] = m.new_int_var(0, HORIZON, f"start_{r.job_id}_{r.step}")
end[key] = m.new_int_var(0, HORIZON, f"end_{r.job_id}_{r.step}")
interval = m.new_interval_var(start[key], r.minutes, end[key], f"op_{r.job_id}_{r.step}")
group = [mid for mid in machines.index if machines.machine_group[mid] == r.machine_group]
if one_of_each:
group = group[:1]
if r.machine_group == "proofer":
proofer.append(interval)
elif len(group) == 1:
on_machine[group[0]].append(interval)
choice[key] = {group[0]: True}
elif len(group) > 1: # either machine: one optional interval each
picks = {}
for mid in group:
p = m.new_bool_var(f"{r.job_id}_{r.step}_on_{mid}")
on_machine[mid].append(m.new_optional_interval_var(start[key], r.minutes, end[key], p, f"{mid}_{key}"))
picks[mid] = p
m.add_exactly_one(picks.values())
choice[key] = picks
if oven_down is not None:
on_machine["OVEN-2"].append(m.new_interval_var(oven_down[0], oven_down[1] - oven_down[0], oven_down[1], "oven2_down"))
for mid, intervals in on_machine.items():
if mid != "PROOFER":
m.add_no_overlap(intervals) # one operation at a time on each machine
if proofer_limit:
m.add_cumulative(proofer, [1] * len(proofer), int(machines.capacity["PROOFER"])) # 4 racks in the proofer
for job, g in ops.groupby("job_id"):
g = g.sort_values("step")
for a, b in zip(g.itertuples(), list(g.itertuples())[1:]):
m.add(start[job, b.step] >= end[job, a.step]) # in order: each step after the one before
if max_wait and a.operation == "proof" and b.operation == "bake":
m.add(start[job, b.step] <= end[job, a.step] + int(rules["max_wait_proof_to_bake"]))
finish = {j: end[j, int(ops[ops.job_id == j].step.max())] for j in jobs.index}
makespan = m.new_int_var(0, HORIZON, "makespan")
m.add_max_equality(makespan, list(finish.values()))
late = {j: m.new_int_var(0, HORIZON, f"late_{j}") for j in jobs.index}
for j in jobs.index:
m.add(late[j] >= finish[j] - int(jobs.due_minute[j]))
if objective == "makespan":
m.minimize(makespan)
else:
m.minimize(1000 * sum(late.values()) + makespan)
m.vars = {"start": start, "end": end, "choice": choice, "makespan": makespan, "late": late}
return m
def solve_schedule(m, ops, work=10.0):
"""Deterministic search with a fixed amount of work (CP-SAT's "deterministic time"), so every run gives the
same schedule on the same OR-Tools version. About 20 seconds on a laptop."""
s = cp_model.CpSolver()
s.parameters.max_deterministic_time = work
s.parameters.num_workers = 8
s.parameters.interleave_search = True
status = s.solve(m)
if status not in (cp_model.OPTIMAL, cp_model.FEASIBLE):
return s, status, None
rows = []
for r in ops.itertuples():
key = (r.job_id, r.step)
picks = m.vars["choice"].get(key)
machine = "PROOFER" if r.machine_group == "proofer" else ("-" if picks is None else
next(mid for mid, p in picks.items() if p is True or s.value(p)))
rows.append((r.job_id, r.step, r.operation, machine, s.value(m.vars["start"][key]), s.value(m.vars["end"][key])))
return s, status, pd.DataFrame(rows, columns=["job_id", "step", "operation", "machine", "start", "end"])
def dispatch_fifo(jobs, ops, machines, one_of_each=False):
"""The head baker's way: jobs in list order, each step as soon as its machine (or a proofer rack) is free."""
free = {mid: 0 for mid in machines.index if mid != "PROOFER"}
proofing = [] # (start, end) of everything in the proofer
rows = []
for job in jobs.index:
ready = 0
for r in ops[ops.job_id == job].sort_values("step").itertuples():
group = [mid for mid in free if machines.machine_group[mid] == r.machine_group]
if one_of_each:
group = group[:1]
if r.machine_group == "proofer":
t = ready
while sum(a < t + r.minutes and t < b for a, b in proofing) >= machines.capacity["PROOFER"]:
t = min(b for a, b in proofing if b > t)
proofing.append((t, t + r.minutes))
machine = "PROOFER"
elif group:
machine = min(group, key=lambda mid: (max(free[mid], ready), mid))
t = max(free[machine], ready)
free[machine] = t + r.minutes
else:
t, machine = ready, "-"
rows.append((job, r.step, r.operation, machine, t, t + r.minutes))
ready = t + r.minutes
return pd.DataFrame(rows, columns=["job_id", "step", "operation", "machine", "start", "end"])
def check_schedule(sched, jobs, machines, rules):
"""Independent check: order of steps, one job per machine at a time, proofer racks, proofing wait. Returns problems."""
problems = []
for job, g in sched.sort_values("step").groupby("job_id"):
rows = list(g.itertuples())
for a, b in zip(rows, rows[1:]):
if b.start < a.end:
problems.append(f"{job}: {b.operation} starts before {a.operation} ends")
if a.operation == "proof" and b.operation == "bake" and b.start - a.end > rules["max_wait_proof_to_bake"]:
problems.append(f"{job}: waits {b.start - a.end} min after proofing (over-proofed)")
for mid, g in sched[~sched.machine.isin(["PROOFER", "-"])].groupby("machine"):
g = g.sort_values("start")
for a, b in zip(g.itertuples(), list(g.itertuples())[1:]):
if b.start < a.end:
problems.append(f"{mid}: {a.job_id} and {b.job_id} overlap")
p = sched[sched.machine == "PROOFER"]
for t in sorted(set(p.start)):
if ((p.start <= t) & (p.end > t)).sum() > machines.capacity["PROOFER"]:
problems.append(f"proofer over capacity at {clock(t)}")
return problems
def summary(sched, jobs):
finish = sched.groupby("job_id").end.max()
late = (finish - jobs.due_minute).clip(lower=0)
return {"makespan": int(finish.max()), "done_at": clock(finish.max()), "late_jobs": int((late > 0).sum()),
"minutes_late": int(late.sum()), "late": {j: int(v) for j, v in late.items() if v > 0}}
dispatch_fifo is the head baker's method: take the jobs in list order, start each step as soon as its machine is free. check_schedule is an independent checker, as on Day 32. Then day34/run_shop.py:
# ---------- 34.1 The data, and the head baker's plan ----------
print(jobs.to_string())
print(ops[ops.job_id.isin(["J01", "J08", "J15", "J17"])].to_string(index=False))
print(machines.to_string())
fifo = dispatch_fifo(jobs, ops, machines)
for p in report("head baker's plan (list order, as soon as possible)", fifo)[:4]:
print(" ", p)
sku category due_minute
job_id
J01 BK-SD bread 420
J02 BK-WW bread 420
J03 BK-03 bread 420
J04 BK-04 bread 420
J05 BK-05 bread 420
J06 BK-SD bread 420
J07 BK-WW bread 420
J08 BK-CR viennoiserie 420
J09 BK-12 viennoiserie 420
J10 BK-13 viennoiserie 420
J11 BK-CR viennoiserie 420
J12 BK-14 viennoiserie 420
J13 BK-20 cake 480
J14 BK-22 cake 540
J15 BK-23 cake 480
J16 BK-25 cookie 480
J17 BK-26 cookie 540
J18 BK-27 cookie 480
job_id step operation machine_group minutes
J01 1 mix mixer 18
J01 2 proof proofer 90
J01 3 bake oven 45
J01 4 pack packing 23
J08 1 laminate laminator 30
J08 2 proof proofer 60
J08 3 bake oven 21
J08 4 pack packing 13
J15 1 mix mixer 23
J15 2 bake oven 49
J15 3 cool none 40
J15 4 decorate decorating 30
J15 5 pack packing 11
J17 1 mix mixer 13
J17 2 bake oven 17
J17 3 pack packing 11
machine_group capacity
machine_id
MIX-1 mixer 1
MIX-2 mixer 1
LAM-1 laminator 1
PROOFER proofer 4
OVEN-1 oven 1
OVEN-2 oven 1
PACK-1 packing 1
DECO-1 decorating 1
head baker's plan (list order, as soon as possible): done at 06:04; 3 late jobs, 137 minutes late; 8 rule breaks
J03: waits 21 min after proofing (over-proofed)
J04: waits 26 min after proofing (over-proofed)
J07: waits 32 min after proofing (over-proofed)
J08: waits 63 min after proofing (over-proofed)
The head baker's plan finishes at 06:04 with 3 late jobs, and 8 doughs wait too long after proofing: the baker's simple rule doesn't see that an oven busy with a cake makes the proofed bread wait. Over-proofed dough collapses in the oven.
34.2 Interval variables and the job-shop model
An interval variable is a start, a length and an end tied together: new_interval_var(start, minutes, end). Three constraints build the whole model:
add_no_overlap(intervals): a machine does one operation at a time.add_cumulative(intervals, demands, capacity): the proofer holds at most 4 racks at once.- For a step that can use either of two machines (two mixers, two ovens), one optional interval per machine, each with a yes/no "present" variable, and
add_exactly_oneof them.
Precedence (start[next] >= end[previous]) keeps each job's steps in order, and start[bake] <= end[proof] + 15 stops dough over-proofing.
# ---------- 34.2 The job-shop model ----------
m = build_schedule(jobs, ops, machines, rules)
solver, status, sched = solve_schedule(m, ops)
print(solver.status_name(status))
report("model, finish as early as possible", sched, solver)
FEASIBLE
model, finish as early as possible: done at 03:14 (no plan can finish before 03:07); 0 late jobs, 0 minutes late; 0 rule breaks
Done at 03:14, nothing late, no rule broken: almost three hours earlier than the head baker's plan, with the same machines and people. CP-SAT reports FEASIBLE, not OPTIMAL: in the work allowed (max_deterministic_time=10, about 20 seconds) it proved only that no plan finishes before 03:07. A 7-minute gap is plenty for a decision; Day 26's lesson applies to CP-SAT too.
max_deterministic_time measures the solver's work in units that don't depend on the computer, so with interleave_search every run gives the same schedule, unlike a limit in seconds.
34.3 What the rules cost
# ---------- 34.3 What the rules cost ----------
for name, kw in [("no proofer limit, no maximum wait", dict(proofer_limit=False, max_wait=False)),
("proofer limit only", dict(max_wait=False))]:
s2, st2, sc2 = solve_schedule(build_schedule(jobs, ops, machines, rules, **kw), ops)
print(f"{name}: done at {summary(sc2, jobs)['done_at']}")
no proofer limit, no maximum wait: done at 03:09
proofer limit only: done at 03:12
Respecting the proofer and the 15-minute limit costs about 5 minutes against a plan that ignores them. The rules are cheap when the schedule is built around them; they are expensive when they're checked after the fact, as in the baker's plan.

Read the Gantt chart: the two ovens are the busiest machines; cakes and cookies go first (they don't need the proofer); breads are mixed early so their 90-minute proof finishes while the ovens are free.
Decision it supports: in what order each machine processes the night's jobs.
Other decisions you can support the same way: print shops · machine shops · hospital operating rooms · software build pipelines · laboratory instruments.
34.4 A short-staffed night
With only one mixer operator and one oven crew, not everything can be ready on time. Now the objective matters.
# ---------- 34.4 A short-staffed night: one mixer, one oven ----------
for objective in ("makespan", "lateness"):
s3, st3, sc3 = solve_schedule(build_schedule(jobs, ops, machines, rules, one_of_each=True, objective=objective), ops)
report(f"one mixer and one oven, objective {objective}", sc3)
print(" late:", {j: f"{v} min" for j, v in summary(sc3, jobs)["late"].items()})
one mixer and one oven, objective makespan: done at 08:04; 7 late jobs, 1102 minutes late; 0 rule breaks
late: {'J03': '174 min', 'J04': '128 min', 'J05': '221 min', 'J10': '67 min', 'J11': '234 min', 'J13': '94 min', 'J16': '184 min'}
one mixer and one oven, objective lateness: done at 09:14; 6 late jobs, 564 minutes late; 0 rule breaks
late: {'J04': '122 min', 'J06': '37 min', 'J07': '197 min', 'J14': '194 min', 'J16': '1 min', 'J17': '13 min'}
- "Finish everything as early as possible" (makespan, proven optimal: 08:04) leaves 7 jobs late by 1,102 minutes in total.
- "Be as little late as possible" finishes later (09:14) but has 6 jobs late by 564 minutes: half the lateness. On a bad night, choose the objective that matches what customers feel.
The planted bug
day34/bug_precedence.py is a colleague's quick version of the model: "each step starts after the step before". Run it.
for job, g in ops.groupby("job_id"):
steps = sorted(g.step)
for a, b in zip(steps, steps[1:]):
m.add(start[job, b] >= start[job, a]) # each step after the one before
What happens, and why
OPTIMAL done at 07:36
57 rule breaks, e.g.:
J01: proof starts before mix ends
J01: bake starts before proof ends
J01: pack starts before bake ends
J02: proof starts before mix ends
"Optimal", and 57 rule breaks: proofing starts before mixing ends, baking before proofing ends. start[b] >= start[a] says the next step starts after the previous one starts; it must be start[b] >= end[a]. With interval variables the end is always there: use it. The checker, written separately, found what the solver couldn't.
Mini-project: can the night crew start later?
The night crew would like to start at 21:30, 22:00 or 22:30 instead of 21:00 (the shift premium is lower before midnight, and it's easier to staff). The 04:00 loading and the cake deadlines don't move. How late can the run start with nothing late?
Solution
"""Day 34 mini-project: the night crew asks to start later. How late can tonight's run start
with nothing late at 04:00 loading?
Run from the repository root (after day06/load_tables.py): python day34/mini_project_start.py (about 1.5 minutes)
"""
import sys
import duckdb
import pandas as pd
sys.path.insert(0, "day34")
from bakery_shop import build_schedule, check_schedule, clock, load_shop, solve_schedule, summary
pd.set_option("display.width", 160)
con = duckdb.connect("northbound.duckdb", read_only=True)
jobs, ops, machines, rules = load_shop(con)
rows = []
for delay in (0, 30, 60, 90):
later = jobs.assign(due_minute=jobs.due_minute - delay) # same clock deadlines, less time to meet them
m = build_schedule(later, ops, machines, rules, objective="lateness")
solver, status, sched = solve_schedule(m, ops)
s = summary(sched, later)
rows.append((clock(delay), clock(s["makespan"] + delay), s["late_jobs"], s["minutes_late"],
", ".join(f"{j} {v}" for j, v in s["late"].items()) or "-",
int(solver.best_objective_bound // 1000), # proven: no plan is less late than this
len(check_schedule(sched, later, machines, rules))))
print(pd.DataFrame(rows, columns=["start", "done_at", "late_jobs", "minutes_late", "late (minutes)", "at_least_late",
"rule_breaks"])
.to_string(index=False))
start done_at late_jobs minutes_late late (minutes) at_least_late rule_breaks
21:00 03:18 0 0 - 0 0
21:30 03:43 0 0 - 0 0
22:00 04:41 0 0 - 0 0
22:30 05:52 1 14 J06 14 2 0
- Starting at 21:30 or 22:00, nothing is late. At 22:00 the run finishes at 04:41, after loading starts, but the last jobs are cakes and cookies due at 05:00 or later.
- At 22:30, at least 2 minutes of lateness can't be avoided: CP-SAT's bound proves it. The plan it found is 14 minutes late on one sourdough job.
Note to the bakery manager: "The night run can start at 22:00 instead of 21:00 with every deadline met. Note that the run then ends at 04:41, so the vans would load the last breads at about 04:00 and the cakes later. Day 37 checks what a later dispatch costs on the road."
Commit
git add .
git commit -m "Day 34: job-shop scheduling of the bakery run"
git push
Day 34 checklist
- I can model a job shop with interval variables,
NoOverlapand precedence. - I can model a machine choice with optional intervals and a shared capacity with
Cumulative. - I can add maximum waits between steps.
- I compare makespan and lateness objectives and say which fits the situation.
- I use deterministic work limits and report the bound with the plan.
- I check schedules with an independent checker.