Maintenance scheduling¶
Derived from the Timefold Quickstarts maintenance-scheduling example
(Apache-2.0; see the repository NOTICE), with modifications:
assigns a crew (Crew) and a start date to maintenance jobs (Job) to minimize early/late
maintenance. A C++ domain on top of the generic engine in core/optimaru/ (late acceptance
+ ALNS), with a Python package (maintenance_scheduling) via pybind11.
Usage¶
OPTIMARU_USE_CASES=maintenance_scheduling uv sync # builds only this use case's C++ extension
uv run pytest -q tests/maintenance_scheduling
from optimaru import maintenance_scheduling as mnt
schedule = mnt.generate_demo_data()
result = mnt.solve(schedule, time_limit_seconds=5.0, random_seed=42)
print(result.score)
solve takes time_limit_seconds, random_seed, parallel_solver_count, stop_at_first_feasible, full_assert, on_new_best, a full config (maintenance_scheduling.SolverConfig) and constraints (see below).
SolverConfig holds the search knobs; optimaru/maintenance_scheduling/_core.pyi lists them. Two of them run destroy-and-repair as an ordinary move judged by the acceptor, besides the kicks on stagnation: ruin_recreate_as_move_weight is the probability that a step draws one (0, the default, turns it off) and ruin_recreate_as_move_max_ruin is its ruin size (12 by default).
The C++ side builds and tests with:
cmake -B build -DOPTIMARU_USE_CASES=maintenance_scheduling && cmake --build build -j
ctest --test-dir build
Domain encoding¶
A Job has two decisions — its crew and its start date (weekdays only) — and
its end date is derived from them.
The engine supports one assignment-shape int value per entity, so both are packed into one
value, the composite encoding pattern of school-timetabling:
crewDate = startDateIndex * crewCount + crewIndex # -1 == unassigned
startDateIndexindexes the list of weekdays (Mon-Fri) of the calendar[fromDate, toDate)(MaintenanceSchedule::startDates;start_dates()in Python).- The end date is a pure function of
(duration, startDateIndex), so it is precomputed into a table (endDateByDur) in the prepare step. It is the exclusive end date skipping weekends (plus_business_daysin Python). - All dates are epoch days (days since 1970-01-01).
C++¶
optimaru/maintenance_scheduling/cpp/mnt/model/domain.hpp— domain +optimaru::SolutionTraitsspecializationoptimaru/maintenance_scheduling/cpp/mnt/constraints/— one component per constraint:min_start_date_cost.hpp,max_end_date_cost.hpp,before_ideal_end_date_cost.hpp,after_ideal_end_date_cost.hpp,crew_conflict_cost.hpp,tag_conflict_cost.hpp(+common.hpp: the per-job and day-overlap bases);optimaru/maintenance_scheduling/cpp/mnt/constraints.hppassembles the default set (defaultConstraints())score_calculator— full recompute (the reference)incremental_calculator— before/after hooks, O(job calendar length) per movesolver— engine wrapper (CH + Late Acceptance + ALNS, guided selection)
Constraints¶
| Constraint (Python name) | C++ component | Default level | Default weight | Raw cost (0 = no violation) |
|---|---|---|---|---|
min_start_date_cost |
MinStartDateCost |
hard | 1 | per (start date, crew) cell: days its jobs start before their min_start_date |
max_end_date_cost |
MaxEndDateCost |
hard | 1 | per cell: days its jobs' (exclusive) end date passes their max_end_date |
before_ideal_end_date_cost |
BeforeIdealEndDateCost |
soft | 1 | per cell: days its jobs end before their ideal_end_date |
after_ideal_end_date_cost |
AfterIdealEndDateCost |
soft | 1,000,000 | per cell: days its jobs end after their ideal_end_date |
crew_conflict_cost |
CrewConflictCost |
hard | 1 | global total: overlapping calendar days summed over same-crew job pairs |
tag_conflict_cost |
TagConflictCost |
soft | 1,000 | global total: shared tags x overlapping days summed over job pairs |
The rows are in list_constraints() order (the four per-job unit constraints first, the two
global ones after them). Every constraint is flippable (level="hard" / level="soft", or
Level.HARD / Level.SOFT; level="medium" raises ValueError, the domain has no medium
level), none is a reward and all six are scored by default (default_enabled);
maintenance_scheduling.constraint_info() reports exactly this table from the C++
components (kDefaultLevel / kDefaultWeight), and the CP-SAT benchmark reads the same
rows. exponent shapes the date constraints per cell and the two global conflict constraints on their
single total. Unassigned jobs contribute nothing.
The _cost suffix separates the constraint names from the job fields min_start_date /
max_end_date. The defaults are declared once, in the C++ components.
Besides weight, level and exponent, every constraint takes offset and clip
(keyword-only), and may be picked several times. A raw cost x (per cell for the four date constraints, the single
total for the two conflict constraints — the granularity of exponent) is shaped as
sign(x) * max(0, |x| - offset) ** exponent (clip=True, the default) or
(x - offset) ** exponent, sign-preserving (clip=False, which lowers the penalty of
every cell below the offset, an empty one included: every crew on every start date);
offset=0 is the plain shaping. Both apply per cell (or to a conflict constraint's one total),
not to the sum over the cells. clip=False with an offset is refused on hard (the two
start/end date constraints and crew_conflict_cost by default), because hard 0 must mean no
violation. Each pick is its own instance with its own knobs, its level included, and the
instances add up:
from optimaru.maintenance_scheduling.constraints import TagConflictCost, get_constraints
mnt.solve(schedule, constraints=[
*get_constraints(), # the defaults
TagConflictCost(weight=100, exponent=2, offset=10), # + 100 x (tag-conflict days beyond 10)^2
])
mnt.constraint_costs(schedule, picks) keys the second pick tag_conflict_cost#2. The
CP-SAT reference takes integral offsets.
Score mapping: this use case scores hard and soft only, so it maps 1:1 onto the engine's Score(int64 hard, double soft), with the soft weights 1 / 1,000 / 1,000,000. The two pairwise constraints reduce to sums of C(n,2) over per-day occupancy counts (equivalent to summing pairwise overlapping days, since the intervals are contiguous) and are scored incrementally in O(job calendar length) per move.
Job::pinned (the engine's pinning hook) — counts in
the score, but the solver never moves it.
Build / run¶
cmake -B build -DCMAKE_BUILD_TYPE=Release -DOPTIMARU_USE_CASES=maintenance_scheduling && cmake --build build -j4
./build/maintenance_scheduling/mnt_test # constraint hand checks + incremental==full + ScoreChecks::Full
./build/maintenance_scheduling/mnt_plugin_test # plugin assembly == monolith, raw costs by hand, catalog, overrides
./build/maintenance_scheduling/mnt_demo # the SMALL demo instance, 10 s, checks hard 0
./build/maintenance_scheduling/mnt_demo 15 --large
OPTIMARU_USE_CASES=maintenance_scheduling uv sync # builds only this use case's C++ extension
uv run pytest -q tests/maintenance_scheduling
The demo data is drawn from a seeded
std::mt19937_64 (seed 17), so it is the same on every platform (SMALL: 3 crews/8 weeks/14 jobs, LARGE: 5 crews/16 weeks/
48 jobs; starting next Monday). Both SMALL and LARGE reach hard 0 within seconds.
Starting from an existing solution¶
with_initial_solution(problem, solution) returns a copy of problem whose search starts from solution, which is MaintenanceScheduleModel.from_core(schedule) or that model as a JSON dict. solve takes the engine object, so convert the result with to_core():
from optimaru.maintenance_scheduling.models import MaintenanceScheduleModel
problem = MaintenanceScheduleModel.from_core(mnt.generate_demo_data())
solved = MaintenanceScheduleModel.from_core(schedule) # `schedule` solved above
restart = mnt.with_initial_solution(problem, solved).to_core()
mnt.solve(restart, time_limit_seconds=5.0, random_seed=43)
print(restart.score)
Jobs are matched by id. A job the solution leaves out is placed by the construction heuristic, and a complete solution is exactly where the search starts. Pinned jobs keep their crew and start date on problem, whatever the solution says. ValueError is raised for an unknown id, for a job with only one of crew_id and start_date, and for a start date that is not a weekday inside the work calendar.
Extending¶
Engine contracts and code skeletons: docs/extending.md.
The solution has the assignment shape; the domain solver that configures the
engine is optimaru/maintenance_scheduling/cpp/mnt/solver.hpp + optimaru/maintenance_scheduling/cpp/mnt/solver.cpp.
Adding a move. The engine already mixes change / swap moves
(weights in Solver::Config). This use case relies on the engine's generic moves only; it has no domain move yet. A new move is a
optimaru::MoveOperator<…> registered with engine.add_move_operator(...) next
to the engine construction in optimaru/maintenance_scheduling/cpp/mnt/solver.cpp; a ruin for LNS is a
RuinOperator registered with engine.add_ruin_operator(...).
Changing the construction heuristic. Entities are placed in index order (First Fit). Set
engineConfig.construction.difficulty for First Fit
Decreasing ordering, or pre-assign part of the solution in the domain
solver's solve before the engine runs — the engine only fills what is still unassigned.
Adding a hard or soft cost. Adding a constraint, step by step takes one new constraint through this use case's files in six steps: changed from Python, written as a component, tested, made cheaper per move, moved to the default fast path and measured.
Benchmark¶
benchmarks/maintenance-scheduling compares this use case with OR-Tools CP-SAT on the same instances.