optimaru.school_timetabling (Python)¶
The Python package wrapping the school-timetabling C++ core (optimaru/school_timetabling/cpp, built on
the engine in core/optimaru/) with pybind11. It moves API_SPEC.md's
canonical TimetableProblem JSON into the canonical C++ domain (st::canon),
solves it, and returns a canonical Timetable JSON.
st::canon has full parity with the CP-SAT reference package
(teacher_scheduling in ../../../benchmarks/school-timetabling/cpsat): it
implements every hard and soft constraint with validate.py's semantics,
under one name per constraint in every layer (the C++ component, the spec,
list_constraints(), constraint_info(), constraint_costs(), the CP-SAT
plugin, the Timetable.penalties keys and the weights keys), and for the
same solution both backends report exactly the same hard-violation count and
weighted soft penalty — benchmarks/school-timetabling/cpsat/tests/test_engine_parity.py injects cpsat solutions
into the engine and gates on that parity.
Install and test¶
OPTIMARU_USE_CASES=school_timetabling uv sync # builds only this use case's C++ extension; pytest + pydantic
uv run pytest -q tests/school_timetabling
Usage¶
from optimaru import school_timetabling as st
result = st.solve(problem_dict, time_limit_seconds=10.0, random_seed=42)
print(result["status"]) # FEASIBLE (hard 0) | INFEASIBLE (hard violations left)
print(result["penalties"]) # raw soft counts, keyed by the soft constraint names (same keys as cpsat)
print(result["objective_value"]) # weighted penalty sum (same unit as cpsat)
for lesson in result["lessons"]:
print(lesson["course_id"], lesson["slot"], lesson["room_id"])
weights={"teacher_gap_cost": 40, ...} changes the soft weights of the
default fast path (canon.SolverConfig.weights, a canon.ObjectiveWeights
keyed by the soft constraint names; the model itself carries no weights) and
config= (the mode's SolverConfig or models.SolveConfig) the search
options. The low-level API is convert_problem /
canon.Solver(canon.SolverConfig) / convert_solution / inject_solution
(injects an external solution, for warm starts and checks); the pydantic
serialization mirrors live in optimaru.school_timetabling.models.
JSON in, JSON out¶
solve_request takes a pydantic request, models.TimetableRequest: the problem as a
models.TimetableProblemModel (the same fields as the TimetableProblem dict) in
model_input, with the settings of the solve under the names of solve's keywords
(time_limit_seconds, random_seed, parallel_solver_count, stop_at_first_feasible,
full_assert, solver_parameters) and this use case's three more, mode, weights and
initial_solution (an earlier TimetableResultModel, or any {"lessons": [...]} whose lessons
carry a course_id and a slot, as solve(initial_solution=...) takes). It returns a
models.TimetableResultModel, the same fields as the
result dict, and leaves the request unchanged.
from optimaru.school_timetabling import solve_request
from optimaru.school_timetabling.models import TimetableRequest
result = solve_request(TimetableRequest(model_input=problem_dict, time_limit_seconds=10.0))
print(result.status, result.penalties)
With an API key set (optimaru.use_api, OPTIMARU_API_KEY), solve_request sends the request
to the optimaru API (POST /api/use-cases/school-timetabling/solve/jobs) and returns the
TimetableResultModel it reads back. solve(problem, ...) goes the same way: the dict and the
keywords become a TimetableRequest (config travels as the request's fields and
solver_parameters; on_new_best, a callback, is refused), and the result comes back as the
dict a local solve returns. A constraints= selection travels as its picks, whether it was
given as specs, names or an Assembly.
See Solving on the optimaru API.
Constraints¶
| Constraint (Python name) | C++ component | Default level | Default weight | Raw cost (0 = no violation) |
|---|---|---|---|---|
unassigned_lessons_cost |
UnassignedLessonsCost |
hard | 1 | weekly periods without a slot (soft weight to use in partial timetabling: UNASSIGNED_LESSONS_SOFT_WEIGHT = 10000) |
class_conflict_cost |
ClassConflictCost |
hard | 1 | pairs of one class's lessons in one period, C(n,2) per (class, period) |
teacher_conflict_cost |
TeacherConflictCost |
hard | 1 | pairs of lessons in one period sharing a teacher, once per shared teacher |
disallowed_slot_cost |
DisallowedSlotCost |
hard | 1 | lessons on a forbidden / unavailable time (engine-only; CP-SAT never creates such a variable) |
room_capacity_cost |
RoomCapacityCost |
hard | 1 | per (special-room type, period): max(0, demand - rooms) |
course_max_periods_per_day_cost |
CourseMaxPeriodsPerDayCost |
hard | 1 | per (course, day): lessons over max_periods_per_day |
block_adjacency_cost |
BlockAdjacencyCost |
hard | 1 | missing same-day adjacencies of a block, plus one per member left out while the rest is placed |
teacher_max_periods_cost |
TeacherMaxPeriodsCost |
hard | 1 | periods over max_periods_per_day per day plus over max_periods_per_week per week |
teacher_max_consecutive_periods_cost |
TeacherMaxConsecutivePeriodsCost |
hard | 1 | per (teacher, day): periods of each run beyond max_consecutive_periods |
teacher_gap_cost |
TeacherGapCost |
soft | 20 | idle periods inside a teacher's day |
teacher_workday_cost |
TeacherWorkdayCost |
soft | 3 | (teacher, day) pairs with any lesson |
teacher_free_day_cost |
TeacherFreeDayCost |
soft | 30 | worked requested free days (a lesson on a preferred_free_days day) |
class_gap_cost |
ClassGapCost |
soft | 10 | idle periods inside a class's day |
avoided_period_cost |
AvoidedPeriodCost |
soft | 5 | lessons in an avoided_periods period (once per member course of a parallel group) |
non_preferred_period_cost |
NonPreferredPeriodCost |
soft | 1 | lessons outside a non-empty preferred_periods |
fixed_slots_cost |
FixedSlotsCost |
hard, not flippable | 1 | lessons off their fixed slot — always 0: fixed lessons are pinned |
parallel_groups_cost |
ParallelGroupsCost |
hard, not flippable | 1 | sections of a parallel group apart — always 0: a group is one merged lesson |
st.constraint_info() reports the same defaults (read off the C++
components' kDefaultWeight / kDefaultLevel), st.constraint_costs(table)
the raw costs of a canon.Timetable, and
optimaru.school_timetabling.constraints.score(costs, selection) the engine score of any
selection, in pure Python.
The quickstart model (mode="quickstart") has no constraint registry; its
seven terms are named room_conflict_cost, teacher_conflict_cost,
class_conflict_cost, teacher_unavailability_cost (hard),
teacher_room_change_cost, teacher_time_efficiency_cost (a reward) and
class_subject_repeat_cost (soft) in its docs and in the benchmark's
school_timetabling_cpsat/evaluate.py.
Plugin constraint assembly (constraints=)¶
The default cost function is the monolithic incremental calculator (fast
path), which scores every constraint above. Passing constraints= switches to
the plugin path next to it: pick constraints per component, change their
weights, move them between hard and soft and drop some.
from optimaru import school_timetabling as st
from optimaru.school_timetabling.constraints import Assembly, ClassConflictCost, TeacherGapCost, get_constraints
print(st.list_constraints()) # the 17 constraint names, in catalog order
result = st.solve(
problem_dict,
time_limit_seconds=10.0,
# Start from the defaults: teacher_gap_cost weight 20 -> 40, teacher_workday_cost dropped.
constraints=Assembly().add("teacher_gap_cost", weight=40).drop("teacher_workday_cost"),
)
# The same entry point as every other use case: None = the defaults, a list replaces them.
result = st.solve(problem_dict, time_limit_seconds=10.0, constraints=[ClassConflictCost(), TeacherGapCost(weight=40)])
# A constraint may be picked several times: the defaults plus the teacher gaps beyond 3, squared.
result = st.solve(
problem_dict,
time_limit_seconds=10.0,
constraints=[*get_constraints(), TeacherGapCost(weight=1, exponent=2, offset=3)],
)
The low-level canon.DecomposedCalculator can score and explain directly:
from optimaru.school_timetabling import canon
from optimaru.school_timetabling.constraints import ClassConflictCost, TeacherConflictCost, TeacherGapCost
calc = canon.DecomposedCalculator([ClassConflictCost(), TeacherConflictCost(), TeacherGapCost(weight=40)])
calc.add("teacher_max_periods_cost", level="soft", weight=5) # demote it to a soft penalty
score = calc.score(converted.table) # score a fixed assignment (stored in table.score)
print(calc.constraint_totals()) # weighted cost per constraint: {name, label, cost, level, is_hard}
Rules:
- Every spec and
addtake the five knobs:weight(None = the component default: 1 for hard, 20/3/30/10/5/1 for the soft ones — neverweights=, which belongs to the fast path and must stay at the defaults next toconstraints=),level(None keeps the default level, otherwise "hard" or "soft", or aLevel; this use case has no medium level, so "medium" raisesValueError),exponent(sign-preserving power shaping) and the keyword-onlyoffset(0.0) /clip(True): with an offset,clip=Truecounts only what lies beyond it (max(0, c - offset) ** exponent),clip=Falseshapesc - offsetas it is (every slot of a per-slot constraint is charged).clip=Falsewith an offset is refused on hard (the pick's level, or the default, the structuralfixed_slots_cost/parallel_groups_costincluded), because hard 0 must mean no violation:ValueError: constraint 'teacher_conflict_cost': clip=False with a non-zero offset cannot be hard, because hard 0 must mean no violation; use clip=True (a threshold) or another level. AnAssemblyholding such a pick is refused where it is used (canon.DecomposedCalculator,solve). Bad names raiseValueError, a wrong knob typeTypeError, in the same words on the Python and the C++ path.fixed_slots_cost/parallel_groups_costrefuselevel="soft". Assembly.addreplaces an existing entry with the same name (override semantics: an Assembly holds each name once); a plain list goes throughget_constraints, where a name picked several times is one instance per pick, each with its own knobs (canon.constraint_costs(table, picks)keys the second"<name>#2");canon.DecomposedCalculator.addadds another instance too. Every pick also takesoffset/clip;offset=0is the plain shaping. Each repeated pick carries its own level:[TeacherGapCost(), TeacherGapCost(level="hard", offset=2)]charges every gap on soft and the gaps beyond two on hard.- The default assembly matches the monolithic score bit for bit (gated by
tests/school_timetabling/test_constraints.pyand the C++st_canonical_plugin_test). penaltiesin thesolveresponse are always the canonical rescore (raw soft counts, independent of the assembly);objective_valueuses the assembly's effective soft weights (a picked soft constraint its weight, the sum of the instances' weights for one picked several times, one left out 0; any non-negative number). Like the exponent,offset/clipshape the search score only;constraints.score(canon.constraint_costs(table, picks), picks)is the selection's exact score.statusfollows the canonical hard rescore too, so an assembly that demotes a hard constraint to soft and ends violating it is INFEASIBLE.unassigned_lessons_costis the exception: demoted to soft, unassigned lessons become a result instead of a violation (the same contract as cpsat'sUnassignedLessonsCost(level="soft")=solve_partial). The search gains unassign moves, so "leave it out" becomes an option; unfilled periods are reported aspenalties["unassigned_lessons_cost"], andstatuscomes from the hard constraints without that term.
# Leave unfillable periods unassigned instead of INFEASIBLE (partial timetabling).
st.solve(
problem_dict,
constraints=Assembly().add("unassigned_lessons_cost", level="soft", weight=st.UNASSIGNED_LESSONS_SOFT_WEIGHT),
)
One unassigned period costs exactly that weight. UNASSIGNED_LESSONS_SOFT_WEIGHT
(10000, C++ UnassignedLessonsCost::kSoftWeight) is the documented soft
weight — above the sum of the other soft terms; weight=None would keep the
component default 1, cheap enough to drop a lesson to save one gap. Do not
use stop_at_first_feasible with this assembly: a solution that drops
everything is hard 0 too and the search would stop there.
- The plugin path is single-start (parallel_solver_count is ignored; a
caller-owned calculator cannot be cloned). When performance comes first, keep
the default fast path.
- Thanks to structural optimisations (compiled delta groups for the per-slot
family, shared projections for the teacher-mask family), the plugin path
runs at a quarter to two thirds of the monolith's steps per second; the rest
of the gap is the fixed cost of the generic assembly dispatch. Measured on
the track-2 schools (gen_canonical.py in
benchmarks/school-timetabling/cpsat/school_timetabling_cpsat/) with
one thread and seeds 1 to 3 (S and M 2 million steps, L 4 million, where
both paths end feasible), the assembly's median rate was 46% of the
monolith's on S, 62% on M and 37% on L, and one seed alone ranged from 25%
(M, seed 1) to 71% (L, seed 1). The rate of both paths moves with the
search, and the two paths do not search alike, so compare them over several
seeds.
Names and weights¶
- Every constraint has one public name,
<subject>_cost, in every layer. fixed_slots_costandparallel_groups_costare real components (always 0, hard, not flippable), solist_constraints()holds 17 names.- The C++ registry names are the struct names (
teacherGapCost). - The canonical model carries no weights;
weight=Noneis the component default everywhere. The fast path'scanon.ObjectiveWeights/SolverConfig.weights/solve(weights=)/models.ObjectiveWeightsModelare keyed by the soft constraint names (teacher_gap_cost, ...) and take any finite number >= 0 (a bool, NaN, infinity or a negative weight raises, as for a constraint pick's weight). A soft constraint added to the catalog gets itsObjectiveWeightsfield when it goes onto the default path (extending.md, step 5). Until then it solves withconstraints=at its pick's weight, the default path does not score it (objective_valueweighs it at its component default), andsolve(weights=)andmodels.ObjectiveWeightsModelrefuse another value for it. Timetable.penaltieskeys are the soft constraint names; partial timetabling reportsunassigned_lessons_cost.canon.constraint_costs(table)is the per-constraint surface;canon.default_calculator()takes no weights.
Canonical conversion (default mode)¶
- Each course becomes
periods_per_weekengine Lessons (id"{course}#k"). - A parallel group (
parallel_group) folds into one merged lesson per weekly period: teacher union, summed special-room demand, class occupancy 1 (the same as cpsat'soccupancy_key). The sections running together (parallel_groups_cost) holds by the merge itself, and each member subject's preferred/avoided periods count separately throughpreference_units, soavoided_period_cost/non_preferred_period_costmatch exactly too. The reverse conversion unfolds it into one canonical lesson per member course. block_periods>= 2 gives that many of the course's lessons a blockGroup, enforcing consecutive periods on one day (block_adjacency_cost, hard).fixed_slots-> pinned lessons (fixed_slots_cost: the engine never moves them);forbidden_slots+ class/teacherunavailable-> a per-lesson allowed_slot table (disallowed_slot_cost, hard).- With team teaching every teacher goes into
teachers, so clashes, caps and gaps are checked for each. required_room_typeis a hard constraint (room_capacity_cost) that demand <= rooms per (type, time); concrete rooms are assigned afterwards by a greedy pass, as in cpsat — it always succeeds on a hard-0 solution.- Per-teacher period caps (
teacher_max_periods_cost,teacher_max_consecutive_periods_cost),preferred_free_days(teacher_free_day_cost) and the per-course daily cap (course_max_periods_per_day_cost) are passed through.
Remaining limits¶
With full parity, what remains are properties of the search and the design, not of expressiveness:
- Local search cannot prove optimality or infeasibility: status is only
FEASIBLE (hard 0) or INFEASIBLE (hard violations left at the time limit —
not a proof), and
best_objective_boundis always null (use the cpsat backend when you need a proof). - Bitmask design limits: periods <= 16, weekday index < 8 (a larger calendar is rejected with ValueError).
- A solution with hard violations left (INFEASIBLE) may report unassigned lessons
or missing special rooms in
notes. On a hard-0 solution notes are always empty.
Quickstart mode (mode="quickstart")¶
The approximate conversion to the 7-term quickstart domain (slotRoom
composite encoding) remains in optimaru.school_timetabling.quickstart. It cannot express
blocks, parallel sections, forbidden times, period caps, preferred periods and
the like, and its soft objective is replaced by the engine's built-in
constraints — every limit is stated in the response notes. See the
quickstart module docstring for details.
Parameters and their costs¶
A request that sets a field which acts only through a cost, while its constraints leave
every such cost out, is refused with ValueError naming the field and the costs to add;
a pick at weight 0 counts. models.parameter_uses(model) lists the fields an input sets,
and Parameters and their costs has the table.
It is checked where the input is the JSON model (solve_request, solve(problem) with constraints=; the weights= path scores every cost); a
compiled problem is solved as given.