Skip to content

optimaru.school_timetabling

Generated from the sources of optimaru/school_timetabling/ and the stubs of its compiled extension. The guide explains the model and the constraints in prose.

optimaru.school_timetabling

School timetabling — Python wrapper of the C++ solver on the optimaru engine.

The default entry point is the canonical full-parity pipeline: convert_problem moves API_SPEC.md's TimetableProblem JSON into the canonical C++ domain (_core.canon, every hard and soft constraint of the CP-SAT reference), local search solves it, and convert_solution turns the result back into a canonical Timetable JSON. solve bundles all of it::

import optimaru.school_timetabling as st

result = st.solve(problem_dict, time_limit_seconds=10.0, random_seed=42)
print(result["status"], result["penalties"], result["notes"])

The quickstart domain (7 teacher/class/room terms, slotRoom composite encoding) remains available through mode="quickstart" and optimaru.school_timetabling.quickstart (an approximate conversion; its limits are in the quickstart module docstring). The top-level classes Timeslot/Room/Lesson/ Timetable/Solver/SolverConfig belong to the quickstart domain; the canonical domain classes live in the canon submodule (canon.Lesson, canon.Timetable, canon.Solver, canon.SolverConfig, canon.ObjectiveWeights, ...). The constraint catalog is the canonical one: list_constraints(), constraint_info() (default level / weight per constraint, read off the C++ components) and constraint_costs(table) (the raw per-constraint costs of a canon.Timetable).

The cost function defaults to the monolithic incremental calculator (fast path); constraints= selects a plugin assembly instead (see constraints.py)::

from optimaru.school_timetabling.constraints import Assembly

result = st.solve(
    problem,
    constraints=Assembly().add("teacher_gap_cost", weight=40).drop("teacher_workday_cost"),
)

A pydantic request (models.TimetableRequest: the problem as models.TimetableProblemModel with the settings of one solve) goes to solve_request, which returns a models.TimetableResultModel. The pydantic mirrors of the engine classes (for serialization) live in optimaru.school_timetabling.models too.

optimaru.school_timetabling.models

Pydantic v2 mirrors of the engine domain — for JSON serialization.

Mirrors _core's Timeslot/Room/Lesson/Timetable and SolverConfig 1:1. The canonical TimetableProblem JSON is handled by convert.py; these models store or send the engine's own shape (debug dumps, regression snapshots, ...)::

from optimaru.school_timetabling.models import TimetableModel, SolveConfig

model = TimetableModel.from_core(table)     # engine -> pydantic
clone = TimetableModel.model_validate_json(model.model_dump_json())
table2 = clone.to_core()                    # pydantic -> engine

TimeslotModel

Bases: StrictModel

One lesson cell: (weekday, period). day 0 = Monday, period is 1-based.

RoomModel

Bases: StrictModel

A room. type is informational (regular/science lab/...) — not a hard constraint in the engine.

LessonModel

Bases: StrictModel

Slot_room is the timeslot*room composite variable (-1 = unassigned).

TimetableModel

Bases: StrictModel

Solution mirror. The score is a read-only result and has its own field.

to_core

to_core() -> _core.Timetable

pydantic -> engine objects (the score field is ignored; the engine recomputes it).

from_core classmethod

from_core(table: Timetable) -> TimetableModel

engine objects -> pydantic (with the current assignment and score).

SolveConfig

Bases: SolveConfigBase

Serializable mirror of _core.SolverConfig / _core.canon.SolverConfig.

The common engine fields are the same in both modes; weights (the fast path's soft weights, keyed by the soft constraint names) applies to canonical mode only (to_canon()) — the quickstart config (to_core()) has no such field.

late_acceptance_size 0 is automatic: clamp(4 * lesson count, 400, 3200) in canonical mode and clamp(8 * lesson count, 400, 3200) in quickstart mode. A positive value is used as it is.

to_canon

to_canon() -> _core.canon.SolverConfig

Canonical-mode config (with the fast path's soft weights).

to_core

to_core() -> _core.SolverConfig

Quickstart-mode config (weights do not exist in the quickstart domain and are ignored).

SlotModel

Bases: StrictModel

One lesson cell: a weekday (0 = Monday) and a 1-based period.

CalendarModel

Bases: StrictModel

Periods per weekday (0 = Monday); days may differ in length.

ClassroomModel

Bases: StrictModel

A special room. room_type is what a subject's required_room_type names.

CourseModel

Bases: StrictModel

One unit to place: a class group, a subject, its teachers and the periods per week.

TimetableProblemModel

Bases: StrictModel

The timetabling problem solve() takes: the pydantic form of the TimetableProblem dict.

ScheduledLessonModel

Bases: StrictModel

One placed period of a course.

TimetableResultModel

Bases: StrictModel

What solve() returns for a TimetableProblemModel: the pydantic form of the Timetable dict.

StartingSlotModel

Bases: BaseModel

The slot of a starting lesson: a weekday (0 = Monday) and a 1-based period; other keys are ignored.

StartingLessonModel

Bases: BaseModel

One placed period of a starting solution: the course and the slot are all a warm start reads.

The other fields of a ScheduledLessonModel may be there or not, and keys this model does not know are ignored, so a result from another backend (a CP-SAT one, with fields of its own) starts a solve as it is, as it does with solve(initial_solution=...).

StartingSolutionModel

Bases: BaseModel

A starting solution that is not a whole TimetableResultModel: {"lessons": [...]} and nothing else needed.

TimetableRequest

Bases: SolveRequest

The timetabling problem with the settings of one solve (see SolveRequest for the shared ones).

mode, weights and initial_solution are the keywords of the same names that only this use case's solve takes.

parameter_uses

parameter_uses(problem: TimetableProblemModel | dict) -> list[ParameterUse]

The parameters problem sets away from their defaults that act only through a cost.

problem is a TimetableProblemModel or the TimetableProblem dict solve() takes. solve() refuses a constraints= selection that holds none of a parameter's costs (optimaru._constraint.require_costs); the default fast path scores every cost. The table is in docs/use-cases/README.md ("Parameters and their costs").

solve_request

solve_request(request: TimetableRequest, *, constraints=None) -> TimetableResultModel

Solve a pydantic request and return the timetable as a TimetableResultModel.

This is solve(problem, ...) on the request's problem as a dict, with the request's settings as the keywords of the same names (see SolveRequest), and constraints the selection solve takes. The request is not changed.

optimaru.school_timetabling.constraints

Canonical constraint specs — an API to build the cost function from plugins.

The default fast path (the monolithic incremental calculator) scores every canonical constraint at its default weight. This module is the optional path next to it: pick constraints one by one, change their weights, flip their hard/soft level, shape their cost, drop some, then pass the selection to solve(problem, constraints=...) or canon.DecomposedCalculator.

The shortest form is :func:get_constraints — without an argument it is the default set, and a list replaces it; a list reads one way, one class call per constraint::

import optimaru.school_timetabling as st
from optimaru.school_timetabling.constraints import ClassConflictCost, TeacherGapCost, get_constraints

st.solve(problem, constraints=get_constraints())               # defaults as they are
st.solve(problem, constraints=[                                # only these two
    ClassConflictCost(), TeacherGapCost(weight=40),
])

:class:Assembly starts from the default set and edits it by name, so "the defaults with a small change" is a one-liner (add replaces the constraint of that name; a plain list is where a constraint is picked several times)::

from optimaru.school_timetabling.constraints import Assembly

st.solve(problem, constraints=Assembly().add("teacher_gap_cost", weight=40).drop("teacher_workday_cost"))

Every spec takes the same five knobs:

  • weight linear multiplier of the constraint's raw cost. None is the component's default weight (the C++ kDefaultWeight: 1 for the hard constraints, 20/3/30/10/5/1 for the six soft ones), never a weight stored anywhere else. st.constraint_info() reports the defaults.
  • level None = the default level, otherwise Level.HARD or Level.SOFT (or the names "hard" and "soft"). This use case has no medium level: level="medium" raises ValueError.
  • exponent sign-preserving power shaping of the cost: weight * sign(c) * |c| ** exponent (per slot for the per-slot constraints, on the single total for the others). 2.0 = squared.
  • offset (keyword) shifts that shaping, at the same granularity; 0.0 = none.
  • clip (keyword) True (the default) counts only what lies beyond the offset, sign(c) * max(0, |c| - offset) ** exponent; False shapes c - offset as it is, so a cost below the offset lowers the penalty (every slot of a per-slot constraint, an empty one included, is charged). With an offset it is refused on hard (TeacherConflictCost and the other hard constraints by default, the structural ones included), because hard 0 must mean no violation.

A constraint may be picked several times in a list; each pick is scored on its own with its own knobs and the picks add up. Teacher gaps plus their square beyond three per week::

st.solve(problem, constraints=[
    *get_constraints(),
    TeacherGapCost(weight=1, exponent=2, offset=3),
])

canon.constraint_costs(table, picks) keys the second pick "teacher_gap_cost#2".

Names are the C++ component names in snake_case (TeacherGapCost -> teacher_gap_cost): the one name of each constraint in every layer — list_constraints(), constraint_info(), constraint_costs(), the CP-SAT reference, the Timetable.penalties keys and the solve weights keys. The module also carries ready-made default instances (teacher_gap_cost is TeacherGapCost(), and so on).

Constraint dataclass

Spec selecting one constraint: weight / level / shaping.

Subclasses set the ClassVars: name (the snake_case registry name the core reports in list_constraints(); required), label_en / label_ko (a short title) and description_en / description_ko (one or two sentences on what one unit of raw cost means). An intermediate base that should not need a name passes abstract=True::

class _RouteLimit(Constraint, abstract=True): ...

offset and clip are keyword-only, so the positional order stays weight, level, exponent followed by a subclass's domain parameters. A name must not contain #, which constraint_costs() keys repeated picks with ("<name>#<k>").

params

params() -> dict[str, Any]

The domain parameters: every dataclass field but the five knobs.

Score

Bases: NamedTuple

Engine-level (hard, soft) from score(). Penalties, so <= 0 without rewards.

A domain with a medium level folds it the way its C++ Score adapter does (into soft, or below hard), so this compares directly with the engine.

UnassignedLessonsCost dataclass

Bases: Constraint

Weekly periods left without a slot. Default: hard, weight 1.

Demoting it with level="soft" gives partial timetabling (the CP-SAT reference's relaxed weekly-period counts): the search gains unassign moves, so "leave it out" becomes an option, and the unfilled periods are reported as penalties["unassigned_lessons_cost"] instead of a hard violation. The weight is then the price of one unassigned period: give it :data:UNASSIGNED_LESSONS_SOFT_WEIGHT (10000) — at the default 1 a lesson would be dropped to save a single teacher gap.

ClassConflictCost dataclass

Bases: Constraint

Pairs of one class's lessons at the same time. Default: hard, weight 1.

TeacherConflictCost dataclass

Bases: Constraint

Pairs of one teacher's lessons at the same time, team teaching included. Default: hard, weight 1.

DisallowedSlotCost dataclass

Bases: Constraint

Lessons on a time their course may not use. Default: hard, weight 1.

Forbidden slots and teacher/class unavailability are folded into one allowed-slot table by the conversion. Engine-only: the CP-SAT reference never creates a variable for such a time.

RoomCapacityCost dataclass

Bases: Constraint

Special-room demand beyond the rooms of that type, per time. Default: hard, weight 1.

CourseMaxPeriodsPerDayCost dataclass

Bases: Constraint

Lessons of a course beyond its daily cap (max_periods_per_day). Default: hard, weight 1.

BlockAdjacencyCost dataclass

Bases: Constraint

How far a block (block_periods consecutive periods) is broken. Default: hard, weight 1.

TeacherMaxPeriodsCost dataclass

Bases: Constraint

A teacher's periods beyond the daily and weekly caps. Default: hard, weight 1.

TeacherMaxConsecutivePeriodsCost dataclass

Bases: Constraint

Periods beyond a teacher's max_consecutive_periods in a row. Default: hard, weight 1.

TeacherGapCost dataclass

Bases: Constraint

Idle periods inside a teacher's day. Default: soft, weight 20.

TeacherWorkdayCost dataclass

Bases: Constraint

(teacher, day) pairs with any lesson. Default: soft, weight 3.

TeacherFreeDayCost dataclass

Bases: Constraint

Worked requested free days: teacher-days with lessons on a preferred free day. Default: soft, weight 30.

ClassGapCost dataclass

Bases: Constraint

Idle periods inside a class's day. Default: soft, weight 10.

AvoidedPeriodCost dataclass

Bases: Constraint

Lessons in a period their subject avoids. Default: soft, weight 5.

A parallel group counts once per member subject.

NonPreferredPeriodCost dataclass

Bases: Constraint

Lessons outside their subject's preferred periods, when it has some. Default: soft, weight 1.

FixedSlotsCost dataclass

Bases: Constraint

Lessons off their course's fixed slots. Default: hard, weight 1; structural, not flippable.

Always 0 in the engine: every fixed slot becomes a pinned lesson the search never moves. level="soft" is refused.

ParallelGroupsCost dataclass

Bases: Constraint

Sections of one parallel group at different times. Default: hard, weight 1; structural, not flippable.

Always 0 in the engine: a parallel group is merged into one lesson per weekly period. level="soft" is refused.

Assembly

Canonical constraint assembly builder. It starts from the whole default set — the same configuration as the monolithic default path — so "the defaults with a small change" stays short.

add inserts a constraint by name (or spec instance) and replaces the one with the same name (override semantics: an Assembly is a builder, it holds each name once; to pick a constraint several times pass a plain list such as [*Assembly(), TeacherGapCost(exponent=2, offset=3)], or use canon.DecomposedCalculator.add directly). drop removes the named constraint. Both return self for chaining::

Assembly().add("teacher_gap_cost", weight=40).drop("teacher_workday_cost")

Assembly(constraints) with an iterable of spec instances/names starts from that list instead of the default set. An Assembly is an iterable of specs, so it goes straight into canon.DecomposedCalculator(assembly).

add

add(constraint: str | Constraint, *, weight: float | None = None, level: Level | str | None = None, exponent: float = 1.0, offset: float = 0.0, clip: bool = True) -> Assembly

Adds a constraint (replacing one with the same name). A name builds a spec from weight/level/exponent/offset/clip; a spec instance is used as is (mixing an instance with keyword overrides raises ValueError). Unknown names raise ValueError.

drop

drop(name: str) -> Assembly

Removes the named constraint from the assembly. ValueError if absent (guards against typos).

list_constraints

list_constraints() -> list[str]

Every constraint name a selection accepts, in catalog order (canon.CONSTRAINT_NAMES).

soft_specs

soft_specs() -> tuple[type[Constraint], ...]

The spec classes that are soft by default, in catalog order — the terms of the objective.

Read off constraint_info() (the C++ kDefaultLevel), so it follows a new soft component by itself.

default_weights

default_weights() -> dict[str, float]

Soft constraint name -> its default weight (the C++ kDefaultWeight, via constraint_info()).

spec_named

spec_named(name: str, *, weight=None, level=None, exponent=1.0, offset=0.0, clip=True) -> Constraint

The spec of the constraint called name with the given knobs; unknown names raise ValueError.

get_constraints

get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]

The cost function as a list of specs: None is the default set (all seventeen, in list_constraints() order); a list replaces it — only the listed constraints are scored::

canon.DecomposedCalculator(get_constraints())          # the defaults
canon.DecomposedCalculator(get_constraints([           # pick and choose
    ClassConflictCost(), TeacherGapCost(weight=40),
]))

The same contract as the C++ applyConstraints: an empty list is an error (not "the defaults"); a constraint named several times is scored once per pick, each with its own knobs. The default set equals what :class:Assembly builds without arguments.

score

score(costs: dict, constraints: list[Constraint] | None = None) -> Score

Scores raw constraint costs with a selection — pure Python, the engine's arithmetic.

costs is canon.constraint_costs(table) (each constraint's raw cost per slot, or its single total, before weight / exponent / offset / level); constraints the selection (None = the defaults). Equals the engine's score of the same assembly on the same table, without a solver. A second pick of a constraint reads the same raw costs with its own knobs::

score(canon.constraint_costs(table), [*get_constraints(), TeacherGapCost(exponent=2, offset=3)])

optimaru.school_timetabling._core

Type stubs for optimaru.school_timetabling._core — the school-timetabling C++ solver.

The compiled module wraps the C++ domain in optimaru/school_timetabling/cpp, which imports the generic engine in core/optimaru. Two domains are exposed:

  • module top level: the quickstart model (Timetable, slotRoom composite encoding, the 7 terms below) and the package's constraint catalog (constraint_info, ConstraintInfo, list_constraints — the canonical domain's; the quickstart model has no registry)
  • canon submodule: the canonical full-parity domain (st::canon), which implements every hard and soft constraint of the CP-SAT reference package (benchmarks/school-timetabling/cpsat) with validate.py's semantics, under the same names.

The quickstart domain uses one assignment-shape int variable per entity (Lesson), so the two variables (timeslot, room) are a single composite encoding::

slot_room = timeslot_index * room_count + room_index   # -1 == unassigned

Score convention: hard counts constraint violations (0 == feasible), soft is the objective. Both are maximised (less negative is better).

Quickstart terms (hard/soft, not selectable): hard 1. room_conflict_cost -1 per pair of lessons in the same timeslot+room hard 2. teacher_conflict_cost -1 per pair of same-teacher lessons in a timeslot hard 3. class_conflict_cost -1 per pair of same-group lessons in a timeslot hard 4. teacher_unavailability_cost -1 per lesson in a timeslot its teacher cannot take soft 5. teacher_room_change_cost -1 per pair of same-teacher lessons in different rooms soft 6. teacher_time_efficiency_cost +1 per pair of same-teacher lessons in consecutive periods of a day (a reward) soft 7. class_subject_repeat_cost -1 per pair of same-group, same-subject lessons in consecutive periods of a day

ConstraintInfo

Bases: NamedTuple

One constraint-catalog row, read off the C++ default assembly.

Score

Two-level score (hard, soft). hard is the integer violation sum (0 == feasible); soft is the objective. Compared lexicographically (hard first).

is_feasible

is_feasible() -> bool

True when hard >= 0: no hard constraint is violated.

Timeslot

Problem fact: one (weekday, period) cell. day 0 = Monday; period is 1-based. (day, period) pairs must be unique within a Timetable.

Room

Problem fact: a classroom or special room. type is informational — not a hard constraint.

Lesson

One lesson to place in the timetable. slot_room is the decision variable (-1 == unassigned); the solver writes it.

slot_room instance-attribute

slot_room: int

timeslot_index * room_count + room_index; -1 == unassigned.

pinned instance-attribute

pinned: bool

True pins slot_room (it is scored but never moved).

Timetable

The solution: the timeslots x rooms grid (value range) + lessons (entities). solve changes the lessons' slot_room and score in place.

Note: list attributes such as lessons return copies, so change the assignment with set_assignment, or set it on the Lessons before building the Timetable.

teacher_unavailable instance-attribute

teacher_unavailable: dict[str, set[int]]

Teacher id -> set of timeslot indices the teacher cannot take. Teachers not listed are always available.

slot_room_count

slot_room_count() -> int

timeslot_count() * room_count() — the size of the slot_room value range.

assignment

assignment() -> list[int]

Current slot_room per lesson (the solution vector).

set_assignment

set_assignment(assignment: list[int]) -> None

Writes slot_room for every lesson. ValueError if the length differs from the lesson count.

SolverConfig

Termination, seed and search options for Solver.

spent_limit_seconds instance-attribute

spent_limit_seconds: float

Wall-clock budget of solve() (default 30 s).

unimproved_spent_limit_seconds instance-attribute

unimproved_spent_limit_seconds: float

Time limit since the last new best; 0 disables it.

step_count_limit instance-attribute

step_count_limit: int

Local-search step budget; 0 disables it.

unimproved_step_count_limit instance-attribute

unimproved_step_count_limit: int

Step limit since the last new best; 0 disables it.

random_seed instance-attribute

random_seed: int

0 is a non-deterministic seed; any other value is reproducible (with several starts and a target that is reached, the start that reaches it first can differ between runs).

parallel_solver_count instance-attribute

parallel_solver_count: int

Independent parallel starts (engine multi-start): worker i gets random_seed+i and the full budget; the best solution wins. A start that reaches best_score_limit stops the others. Default 1.

late_acceptance_size instance-attribute

late_acceptance_size: int

Late-acceptance queue length. 0 (default) = auto: clamp(8 * lesson count, 400, 3200).

full_assert instance-attribute

full_assert: bool

True checks the incremental score against a full recompute after every move (debugging; very slow).

ruin_recreate instance-attribute

ruin_recreate: bool

Enables adaptive ruin-and-recreate kicks on stagnation.

ruin_recreate_unimproved_step_trigger instance-attribute

ruin_recreate_unimproved_step_trigger: int

Minimum unimproved steps before a kick.

ruin_recreate_min_ruin_fraction instance-attribute

ruin_recreate_min_ruin_fraction: float

Minimum fraction of entities ruined per kick.

ruin_recreate_max_ruin_fraction instance-attribute

ruin_recreate_max_ruin_fraction: float

Maximum fraction of entities ruined per kick.

ruin_recreate_max_ruin_count instance-attribute

ruin_recreate_max_ruin_count: int

Absolute cap on the entities ruined per kick.

ruin_recreate_operator_decay instance-attribute

ruin_recreate_operator_decay: float

Adaptive operator-weight decay; higher adapts more slowly.

ruin_recreate_rewards instance-attribute

ruin_recreate_rewards: list[float]

Rewards per outcome NEW_BEST / BETTER / ACCEPTED / REJECTED (exactly 4).

ruin_recreate_polish_steps instance-attribute

ruin_recreate_polish_steps: int

Small hill-climbing polish steps per kick.

ruin_recreate_as_move_weight instance-attribute

ruin_recreate_as_move_weight: float

Relative weight of destroy&repair mixed in as an ordinary move judged by the acceptor. Negative (default) = auto: 0.2 / slotRoomCount when slotRoomCount lies in the measured benefit band [900, 1300], else 0 (benchmarks/school-timetabling/RESULTS.md). 0 disables it; a positive value is used as is. One as-move costs ruin count x slotRoomCount evaluations.

ruin_recreate_as_move_max_ruin instance-attribute

ruin_recreate_as_move_max_ruin: int

Cap on the lessons one as-move ruins (default 12).

descent_weight instance-attribute

descent_weight: float

Relative weight of the best-improvement descent over nearby lesson pairs (default 0 = off; measured weaker than the as-move in this domain, benchmarks/school-timetabling/RESULTS.md).

descent_max_sweeps instance-attribute

descent_max_sweeps: int

Maximum sweeps per descent (default 4).

change_move_weight instance-attribute

change_move_weight: float

Relative weight of the assignment-shape change move; 0 disables it.

swap_move_weight instance-attribute

swap_move_weight: float

Relative weight of the assignment-shape swap move; 0 disables it.

best_score_limit instance-attribute

best_score_limit: tuple[int, float]

Stops early once bestScore >= (hard, soft) (lexicographic). (0, -inf) stops at the first feasible solution. Default: unreachable.

on_new_best instance-attribute

on_new_best: Callable[[int, Score], None] | None

Called on every new best solution: on_new_best(step, score). The GIL is re-acquired on entry (safe from multi-start worker threads too).

same_group_nearby instance-attribute

same_group_nearby: bool

Registers lessons of the same studentGroup as nearby neighbours (swap partner bias + related ruin). Default True.

same_group_nearby_probability instance-attribute

same_group_nearby_probability: float

Probability of drawing the swap partner from the nearby (same group) list (default 0.5).

Solver

Local-search solver (construction heuristic + late acceptance + ALNS). Solves IN PLACE: writes lesson.slot_room and table.score. Pinned lessons keep their assignment.

canon

Canonical full-parity domain submodule (st::canon).

At runtime this is the optimaru.school_timetabling._core.canon module (written as a namespace class in the stub). Implements every constraint of the CP-SAT reference with validate.py's semantics (raw cost; 0 = no violation):

hard: unassigned_lessons_cost (lessons without a slot), class_conflict_cost / teacher_conflict_cost (C(n,2) clashes), disallowed_slot_cost (placed outside allowed_slot), room_capacity_cost (demand over the special rooms per type and time), course_max_periods_per_day_cost (over a course's daily cap), block_adjacency_cost (broken blocks), teacher_max_periods_cost (daily + weekly caps), teacher_max_consecutive_periods_cost (consecutive-lessons cap), fixed_slots_cost / parallel_groups_cost (structural, always 0: pinned and merged lessons; not flippable) soft: teacher_gap_cost (20), teacher_workday_cost (3), teacher_free_day_cost (30, worked requested free days), class_gap_cost (10), avoided_period_cost (5), non_preferred_period_cost (1)

Design limits: periods <= 16, weekday index < 8 (bitmasks; prepare rejects more).

CONSTRAINT_NAMES instance-attribute

CONSTRAINT_NAMES: tuple[str, ...]

Every name a selection accepts, in catalog order: unassigned_lessons_cost, class_conflict_cost, teacher_conflict_cost, disallowed_slot_cost, room_capacity_cost, course_max_periods_per_day_cost, block_adjacency_cost, teacher_max_periods_cost, teacher_max_consecutive_periods_cost (hard, weight 1), teacher_gap_cost (20), teacher_workday_cost (3), teacher_free_day_cost (30), class_gap_cost (10), avoided_period_cost (5), non_preferred_period_cost (1) (soft), fixed_slots_cost, parallel_groups_cost (hard, structural). constraint_info() reports the same defaults.

UNASSIGNED_LESSONS_SOFT_WEIGHT instance-attribute

UNASSIGNED_LESSONS_SOFT_WEIGHT: float

The documented weight of unassigned_lessons_cost demoted to soft (partial timetabling): 10000 per unplaced period. A recommendation, not a default.

ObjectiveWeights

Soft weights of the monolithic fast path (SolverConfig.weights), keyed by the soft constraint names; the defaults are the components' kDefaultWeight (20/3/30/10/5/1). 0 drops the term. Never part of the model and never read by the plugin path. The constructor and the field setters take a real number, finite and >= 0, like a constraint pick's weight knob (TypeError for a bool or a non-number, ValueError otherwise).

Lesson

One weekly hour of a (possibly merged) course. slot is the decision variable (timeslot index, -1 == unassigned).

teachers instance-attribute
teachers: list[int]

Dense ids of every teacher teaching the lesson (team teaching >= 2, merged lessons take the union).

room_type_demand instance-attribute
room_type_demand: list[int]

Demand per special-room type (room_capacity_cost). Empty list = no demand.

allowed_slot instance-attribute
allowed_slot: list[bool]

Per-slot allowance table (disallowed_slot_cost). Empty list = everything allowed.

preference_units instance-attribute
preference_units: list[tuple[int, int]]

avoided_period_cost / non_preferred_period_cost units: one (avoided mask, preferred mask) pair per member course (bit = period - 1). Empty means derived from the course_key masks.

block_group instance-attribute
block_group: int

Block (consecutive periods) group id (block_adjacency_cost), -1 = none.

pinned instance-attribute
pinned: bool

True pins the slot (fixed slots: the engine never moves it).

Timetable

Problem and solution in one object. Slots are enumerated as (day_of_slot[s], period_of_slot[s]) — days may have different period counts; list only the cells that exist.

room_capacity_by_type instance-attribute
room_capacity_by_type: list[int]

Number of rooms per special-room type (room_capacity_cost).

teacher_max_per_week instance-attribute
teacher_max_per_week: list[int]

-1 = unlimited (cpsat's None).

teacher_preferred_free_days instance-attribute
teacher_preferred_free_days: list[int]

Per-teacher requested-free-day bitmask (bit d = 0-based weekday).

assignment
assignment() -> list[int]

Current slot per lesson (the solution vector).

set_assignment
set_assignment(assignment: list[int]) -> None

Writes the slot of every lesson. ValueError if the length differs from the lesson count.

ConstraintSpec

Bases: Protocol

Constraint-pick duck type: the Constraint specs of optimaru.school_timetabling.constraints and Assembly items qualify. weight None = the component default, level None = the default level (otherwise "hard" or "soft", or a Level; this use case has no medium level). offset / clip are optional (0.0 / True).

ConstraintTotalDict

Bases: TypedDict

cost instance-attribute
cost: float

Total after weighting; positive = penalty.

DecomposedCalculator

Plugin-style cost assembly: pick constraints, change weights and flip hard/soft levels, then pass it to Solver.solve(table, calc) or score a fixed assignment directly.

Assemble from constraint picks (an Assembly / spec list from optimaru.school_timetabling.constraints) or add names one by one with :meth:add. The default set (:func:default_calculator) matches :func:calculate_score bit for bit.

delta_group_count property
delta_group_count: int

Number of structural delta groups compiled by the last reset/solve.

add
add(name: str, weight: float | None = None, level: str | None = None, exponent: float = 1.0, *, offset: float = 0.0, clip: bool = True) -> None

Adds one canonical constraint by name (CONSTRAINT_NAMES).

linear multiplier of the raw cost; None keeps the

component default.

level: None keeps the default level, otherwise "hard" or "soft" (fixed_slots_cost / parallel_groups_cost refuse "soft"). exponent: sign-preserving power shaping: contribution = weight * sign(c)|c|^exponent. offset: (keyword) shifts that shaping (0.0 = none): with clip=True (the default) weight * sign(c)max(0, |c| - offset)^exponent, with clip=False weight * (c - offset)^exponent (sign- preserving; every slot of a per-slot constraint is charged), refused with an offset on hard (ValueError: hard 0 must mean no violation). Unknown names raise ValueError. Adding a name twice is allowed (the costs add up).

score
score(table: Timetable) -> Score

Scores table's current assignment with this assembly (also stored in table.score). Afterwards :meth:constraint_totals explains it.

constraint_totals
constraint_totals() -> list[canon.ConstraintTotalDict]

Weighted cost per constraint of the last score/solve (the score explanation), in list_constraints() order.

constraint_costs
constraint_costs(table: Timetable) -> dict[str, dict[str, Any]]

Raw per-unit costs of this assembly's constraints on table (the canon.constraint_costs shape; re-primes the calculator).

SolverConfig

Configuration of canon.Solver. The common engine fields match the top-level SolverConfig; canonical-only additions are the fast path's weights and the guided-search knobs (hot_lesson_probability, same_class_nearby*, smart_class_swap_*).

late_acceptance_size instance-attribute
late_acceptance_size: int

0 = auto: clamp(4 * lesson count, 400, 3200). A positive value is used as is.

ruin_recreate_as_move_weight instance-attribute
ruin_recreate_as_move_weight: float

Relative weight of the destroy&repair as-move (default 0 = off — unlike the quickstart side there is no auto rule; negative also means off).

weights instance-attribute
weights: ObjectiveWeights

The soft weights of the monolithic fast path, solve(table) only (the model carries none; the plugin path's components carry their own).

hot_lesson_probability instance-attribute
hot_lesson_probability: float

Probability of picking a lesson involved in a hard violation as the move target (0 = off).

same_class_nearby instance-attribute
same_class_nearby: bool

Registers lessons of the same class as nearby neighbours (swap partner / related ruin).

smart_class_swap_moves instance-attribute
smart_class_swap_moves: bool

Best-of-k same-class swap custom move (k evaluations, soft phase only).

reassign_candidates instance-attribute
reassign_candidates: int

Placements tried when putting an unassigned lesson back (partial timetabling only).

Used only when the assembly demotes unassigned_lessons_cost to soft. Re-inserting into a tight timetable needs a slot that clashes with nobody, which a single random cell almost never finds — looking wide is the point of this move, hence a larger k than the swap's. Track-3 sweep (partial_M, 10 s): 8 -> 325 cells, 16 -> 328, 32 -> 342, 64 -> 341.

Solver

Canonical-domain local-search solver (allowed_slot-based value recommender + FFD construction order + ALNS). Solves IN PLACE.

prepare staticmethod

prepare(table: Timetable) -> None

Normalises the instance (idempotent; calculate_score / constraint_costs / solve call it too). Invalid input raises ValueError.

constraint_costs staticmethod

constraint_costs(table: Timetable, constraints: Iterable[ConstraintSpec] | None = None) -> dict[str, dict[str, Any]]

Raw per-unit cost of every default constraint (or of the picked ones), before weight/exponent/offset/level, in list_constraints() order: {key: {"costs": [...], "weight": float, "exponent": float, "offset": float, "clip": bool, "global": bool, "level": "hard" | "medium" | "soft", "reward": bool, "level_flippable": bool, "name": str, "label": str, "default_weight": float, "default_level": str}}. "costs" holds one value per slot for the per-slot constraints, one total for the others. A name picked several times is keyed "#" from its second pick on, next to its first. optimaru.school_timetabling.constraints.score(costs, selection) turns it into the engine score of any selection.

default_calculator staticmethod

default_calculator() -> canon.DecomposedCalculator

A DecomposedCalculator with the default set, every component at its default weight and level (scores like calculate_score).

constraint_info

constraint_info() -> list[ConstraintInfo]

The constraint catalog of the canonical domain, in list_constraints() order: per constraint its Python name, default level, default weight (the C++ kDefaultWeight), whether a pick's level may change it (False for fixed_slots_cost / parallel_groups_cost), whether it is a reward, and whether it is scored by default.

list_constraints

list_constraints() -> list[str]

The canonical constraint names, in catalog order (= canon.CONSTRAINT_NAMES).

calculate_score

calculate_score(table: Timetable) -> Score

Full recompute of all 7 constraints (also stored in table.score).