Skip to content

optimaru.maintenance_scheduling

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

optimaru.maintenance_scheduling

Maintenance scheduling — Python wrapper of the C++ solver on the optimaru engine.

Assigns maintenance jobs (Job) a crew and a start date (weekdays only). The two decisions (crew, start date) are composite-encoded into one engine assignment-shape variable::

crew_date = start_date_index * crew_count + crew_index   # -1 == unassigned

Dates are exchanged as epoch days (days since 1970-01-01). The pydantic mirror (optimaru.maintenance_scheduling.models) converts to and from datetime.date.

Constraints, at the default weights: hard 1. crew_conflict_cost -overlapping days per overlapping job pair on the same crew hard 2. min_start_date_cost -1 per day started before min_start_date hard 3. max_end_date_cost -1 per day ended after max_end_date soft 4. before_ideal_end_date_cost -1 per day ended before ideal_end_date soft 5. after_ideal_end_date_cost -1'000'000 per day ended after ideal_end_date soft 6. tag_conflict_cost -1'000 per shared tag x overlapping day of overlapping job pairs Change a weight or a level through a constraint selection, e.g. solve(schedule, constraints=[..., TagConflictCost(weight=10_000)]) (see optimaru.maintenance_scheduling.constraints). constraint_info() lists every constraint with its default level and weight.

Usage::

import optimaru.maintenance_scheduling as mnt

schedule = mnt.generate_demo_data("SMALL")
mnt.solve(schedule, time_limit_seconds=10.0, random_seed=42)
print(schedule.score, schedule.score.is_feasible())

optimaru.maintenance_scheduling.models

Pydantic v2 mirror of the engine domain — for JSON serialization/deserialization.

Mirrors _core's Crew/Job/MaintenanceSchedule 1:1, but dates are handled as datetime.date (epoch day integers on the engine side). Assignments are stored as a human-readable (crew_id, start_date) pair instead of the composite crew_date, and end_date (derived, weekends skipped) is a result-only field::

from optimaru.maintenance_scheduling.models import MaintenanceScheduleModel

model = MaintenanceScheduleModel.from_core(schedule)  # engine -> pydantic
clone = MaintenanceScheduleModel.model_validate_json(model.model_dump_json())
schedule2 = clone.to_core()                           # pydantic -> engine

CrewModel

Bases: StrictModel

A crew. One crew can do at most one job per day.

JobModel

Bases: StrictModel

A maintenance job. crew_id/start_date are the assignment (both set means assigned), end_date is derived, weekends skipped (result only, ignored by to_core).

MaintenanceScheduleModel

Bases: StrictModel

Pydantic mirror of the schedule. score is a read-only result, kept as a separate field.

to_core

to_core() -> _core.MaintenanceSchedule

pydantic -> engine object. The crew_id/start_date assignment is encoded as the composite crew_date value (start_date must be a weekday within the calendar).

from_core classmethod

from_core(schedule: MaintenanceSchedule) -> MaintenanceScheduleModel

engine object -> pydantic (including the current assignment, the derived end_date and score).

MaintenanceScheduleRequest

Bases: SolveRequest

The maintenance schedule with the settings of one solve (see SolveRequest for those).

date_to_epoch

date_to_epoch(d: date) -> int

datetime.date -> epoch day (days since 1970-01-01).

epoch_to_date

epoch_to_date(epoch_day: int) -> date

epoch day -> datetime.date.

with_initial_solution

with_initial_solution(problem, solution)

Return a copy of problem whose search starts from solution.

solution is what a solve returns (MaintenanceScheduleModel.from_core), or a plain dict of that shape (the JSON the API returned). Jobs are matched by id. A job left out becomes unassigned and the construction heuristic places it, and only it, so a complete solution starts the search exactly from it. problem is not mutated. Pinned jobs keep their crew and start date on problem, whatever solution says.

Raises ValueError naming the job for an unknown or repeated id, for a crew_id or start_date set without the other, for an unknown crew and for a start_date that is not a weekday inside the work calendar. end_date is derived: it is cleared here and the solve fills it in again.

parameter_uses

parameter_uses(model: MaintenanceScheduleModel) -> list[ParameterUse]

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

solve refuses a selection that holds none of a parameter's costs (optimaru._constraint.require_costs); the table is "Parameters and their costs" in docs/use-cases/README.md.

solve_request

solve_request(request: MaintenanceScheduleRequest, *, constraints=None) -> MaintenanceScheduleModel

Solve a pydantic request and return the solved problem model.

This is solve(request.model_input, ...) 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.maintenance_scheduling.constraints

Constraint assembly specs — an API for picking the cost function declaratively.

The default path (mnt.solve(schedule)) enables all six constraints at their default weights. This module is the alternative path next to it: pick constraints, change weights, change levels, shape the cost, and pass the list to solve(schedule, constraints=...).

A constraint list reads one way: one class call per constraint::

import optimaru.maintenance_scheduling as mnt
from optimaru.maintenance_scheduling.constraints import (
    CrewConflictCost, TagConflictCost, get_constraints,
)

mnt.solve(schedule, constraints=get_constraints())          # the defaults as-is
mnt.solve(schedule, constraints=[                           # picked
    CrewConflictCost(), TagConflictCost(weight=10_000),
])

Only listed constraints are scored — leave one out and its term disappears from the score. (The module also carries ready-made default instances: crew_conflict_cost is CrewConflictCost(), and so on.)

Every spec takes five knobs:

  • weight linear multiplier on the constraint cost. None = the component default (MinStartDateCost, MaxEndDateCost, CrewConflictCost and BeforeIdealEndDateCost 1, TagConflictCost 1000, AfterIdealEndDateCost 1'000'000); mnt.constraint_info() reports them.
  • 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: weight * sign(c) * |c| ** exponent. 2.0 = squared, so concentrated violations grow much costlier. The four date constraints shape per (start date, crew) cell; the two global conflict constraints shape their single total.
  • offset (keyword) shifts that shaping, at the same granularity; 0.0 = none.
  • clip (keyword) True (the default) counts only what lies beyond the offset, max(0, c - offset) ** exponent; False shapes c - offset as it is, so a cell below the offset — an empty one (cost 0) included, every crew on every start date — lowers the penalty, and a global total below it does too. With an offset it is refused on hard (MinStartDateCost, MaxEndDateCost and CrewConflictCost by default), because hard 0 must mean no violation.

The same constraint may be picked several times; each pick is scored on its own with its own knobs (its level included) and the picks add up. A tag-conflict day costs 1000, and the total beyond ten days costs its square on top::

mnt.solve(schedule, constraints=[
    *get_constraints(),
    TagConflictCost(weight=100, exponent=2, offset=10),
])

mnt.constraint_costs(schedule, picks) keys the second pick "tag_conflict_cost#2".

The weight ratio of the three soft terms (1 : 1'000 : 1'000'000) is the character of this domain — lateness is a thousand times a tag conflict and a million times early completion.

Names (name) are the C++ component names in snake_case (CrewConflictCost -> crew_conflict_cost). The core derives them mechanically, so there is no hand-maintained alias table — check them with mnt.list_constraints(). Module-level instance names use the same snake_case, so they match the strings list_constraints() prints. (The _cost suffix also keeps the constraint names apart from the job fields min_start_date / max_end_date they read.)

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.

Level

Bases: StrEnum

The score level a constraint is charged on. Hard dominates medium, medium dominates soft.

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.

MinStartDateCost dataclass

Bases: Constraint

Calendar days a job starts before its earliest start date. Default: hard, weight 1.

MaxEndDateCost dataclass

Bases: Constraint

Calendar days a job ends after its end deadline. Default: hard, weight 1.

BeforeIdealEndDateCost dataclass

Bases: Constraint

Calendar days a job ends before its ideal end date. Default: soft, weight 1.

The cheapest of the three soft terms by design — bringing maintenance forward throws away remaining service life, but that loss is light.

AfterIdealEndDateCost dataclass

Bases: Constraint

Calendar days a job ends after its ideal end date. Default: soft, weight 10^6.

A thousand times a tag conflict and a million times early completion — which is why this is the soft term the search clears first.

CrewConflictCost dataclass

Bases: Constraint

Calendar days two jobs of the same crew overlap. Default: hard, weight 1.

Each crew owns one row, so a job occupies exactly one row for the days it runs. Two jobs of the same crew can sit in different (start date, crew) cells, so this is a global constraint.

TagConflictCost dataclass

Bases: Constraint

Calendar days two jobs sharing a tag overlap. Default: soft, weight 1000.

Counted once per shared tag. Each tag owns one row, so a job occupies as many rows as it carries tags. Global for the same reason as crew_conflict_cost.

get_constraints

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

Return the cost function. Without arguments, all six default constraints.

When constraints is given, that list is used as-is — only the listed constraints are scored::

get_constraints([CrewConflictCost(), TagConflictCost(weight=10_000)])

Same contract as the C++ applyConstraints: an empty list (most likely a filter that came out empty) raises ValueError; a constraint named several times is scored once per pick, each with its own knobs.

score

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

Apply specs to raw constraint costs and produce a score — pure Python.

costs is what mnt.constraint_costs(schedule) returns: per constraint, the raw cost of each unit (before weight, exponent, offset and level rounding). Fetch it once and rescore with different weights without re-solving::

raw = mnt.constraint_costs(schedule)
score(raw)                     # default set
score(raw, [CrewConflictCost(), TagConflictCost(weight=10_000)])
score(raw, [TagConflictCost(), TagConflictCost(exponent=2, offset=10)])

No solver and no search are involved. The arithmetic matches the engine — each unit contributes weight * shape(cost, exponent, offset, clip) and hard contributions are rounded per unit before summing (the same order as the engine's applyRaw; rounding the total afterwards gives different values). A second pick of a constraint reads the same raw costs with its own knobs.

When constraints is given, only those constraints are scored — the same semantics as get_constraints. Unknown names raise ValueError.

optimaru.maintenance_scheduling._core

Type stubs for optimaru.maintenance_scheduling._core — the maintenance-scheduling C++ solver.

The compiled module wraps the C++ domain in optimaru/maintenance_scheduling/cpp, which imports the generic engine in core/optimaru.

The two decisions per job (crew, start date) are composite-encoded into one assignment-shape int variable per entity (Job)::

crew_date = start_date_index * crew_count + crew_index   # -1 == unassigned

start_date_index indexes the list of weekdays (Mon-Fri) of the calendar [from_date, to_date) (MaintenanceSchedule.start_dates()). All dates are epoch days (days since 1970-01-01), and a job's derived end date is the exclusive end date reached by advancing duration days while skipping weekends (plus_business_days).

Score convention: hard is the sum of constraint-violating days (0 == feasible), soft is the optimization objective. Both are maximized (less negative is better).

Constraints (hard/soft; days are calendar days), at the default weights: hard 1. crew_conflict_cost -overlapping days per overlapping job pair on the same crew hard 2. min_start_date_cost -1 per day started before min_start_date hard 3. max_end_date_cost -1 per day ended after max_end_date soft 4. before_ideal_end_date_cost -1 per day ended before ideal_end_date soft 5. after_ideal_end_date_cost -1'000'000 per day ended after ideal_end_date soft 6. tag_conflict_cost shared tags x overlapping days of overlapping job pairs -1'000

Score

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

is_feasible

is_feasible() -> bool

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

Crew

Problem fact: a crew. It can do at most one job per day.

Job

A maintenance job to assign. crew_date is the decision variable (-1 == unassigned), written by the solver. Dates are epoch days.

duration_in_days instance-attribute

duration_in_days: int

Working days (business days, weekends excluded).

min_start_date instance-attribute

min_start_date: int | None

inclusive; None = no limit.

max_end_date instance-attribute

max_end_date: int | None

exclusive; None = no limit.

ideal_end_date instance-attribute

ideal_end_date: int | None

exclusive; None = no ideal end date.

crew_date instance-attribute

crew_date: int

start_date_index * crew_count + crew_index; -1 == unassigned.

pinned instance-attribute

pinned: bool

If True, crew_date is fixed (it counts in the score but never moves).

MaintenanceSchedule

The problem and its solution: the calendar [from_date, to_date) x crews grid (value range) + jobs. solve changes the jobs' crew_date and score in place.

Note: list attributes such as jobs return copies, so to change assignments use set_assignment or assign the whole list again.

date_count

date_count() -> int

Size of the start date value range (weekdays in the calendar).

start_dates

start_dates() -> list[int]

Start date value range: the weekday epoch days of [from_date, to_date).

job_start_date

job_start_date(job_index: int) -> int | None

Assigned start epoch day; None when unassigned.

job_end_date

job_end_date(job_index: int) -> int | None

Derived end date (exclusive; skips weekends); None when unassigned.

SolverConfig

Engine settings (default: 30 s budget, late acceptance + ALNS).

late_acceptance_size instance-attribute

late_acceptance_size: int

0 = auto: clamp(8 * jobs, 400, 3200). The first stage's length: the search restarts with a doubled history when it stalls and the next stage fits in the budget. A solve that starts from a given solution keeps this one length.

full_assert instance-attribute

full_assert: bool

If True, re-checks incremental == full on every move (for debugging; very slow).

ruin_recreate_as_move_weight instance-attribute

ruin_recreate_as_move_weight: float

Destroy-and-repair as an ordinary acceptor-judged move (the engine's ruin_recreate.as_move_weight). 0 (default) = off.

ruin_recreate_as_move_max_ruin instance-attribute

ruin_recreate_as_move_max_ruin: int

Ruin size for the as-a-move form; much smaller than a kick's.

window_value_probability instance-attribute

window_value_probability: float

Probability that a change move draws a date from the job's own [minStart, idealEnd] start window. 0 draws uniformly from all of (date x crew).

hot_job_probability instance-attribute

hot_job_probability: float

Probability of seeding a move with a job currently caught in tag_conflict_cost.

free_crew_candidates instance-attribute

free_crew_candidates: int

Random crews a guided change move tries to find one free for the whole job duration. 0 draws uniformly.

best_score_limit instance-attribute

best_score_limit: tuple[int, float]

Stop early once bestScore >= (hard, soft). (0, -inf) stops at the first feasible.

Solver

solve

solve(schedule: MaintenanceSchedule) -> None

Solves in place: writes jobs[*].crew_date and schedule.score. Pinned jobs keep their assignment.

solve_with_constraints

solve_with_constraints(schedule: MaintenanceSchedule, constraints: Iterable[Any] | None = ...) -> None

Score the same solve with a caller-chosen constraint set (see optimaru.maintenance_scheduling.constraints). The given list replaces the default set; None keeps the default set. A name may be picked several times: each pick is its own instance with its own knobs, and the instances add up.

ConstraintInfo

Bases: NamedTuple

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

calculate_score

calculate_score(schedule: MaintenanceSchedule) -> Score

Full recalculation (also stored in schedule.score).

plus_business_days

plus_business_days(start_date: int, business_days: int) -> int

The exclusive end epoch day reached by advancing business_days while skipping weekends.

generate_demo_data

generate_demo_data(size: str = 'SMALL', from_date: int | None = None) -> MaintenanceSchedule

A demo instance (deterministic, seed 17). SMALL: 3 crews/8 weeks/14 jobs, LARGE: 5 crews/16 weeks/48 jobs. from_date defaults to next Monday; for reproducible tests pass a fixed Monday epoch day.

list_constraints

list_constraints() -> list[str]

Constraint names scored by this domain (snake_case; the four per-job unit constraints first, the two global ones after them): min_start_date_cost, max_end_date_cost, before_ideal_end_date_cost, after_ideal_end_date_cost, crew_conflict_cost, tag_conflict_cost. The same names optimaru.maintenance_scheduling.constraints uses.

constraint_costs

constraint_costs(schedule: MaintenanceSchedule, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]

Raw cost of every constraint, before weight/exponent/offset/level rounding: {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}}. The four date constraints list one cost per (start date, crew) cell, an empty cell included; the two global conflict constraints one total. None = the default constraints; a pick list (as for solve) scores exactly those picks, each entry carrying its pick's knobs, the k-th pick of a name keyed "#" from the second on. optimaru.maintenance_scheduling.constraints.score() takes these and produces a score.

constraint_info

constraint_info() -> list[ConstraintInfo]

The constraint catalog, in list_constraints() order: min_start_date_cost (hard, 1), max_end_date_cost (hard, 1), before_ideal_end_date_cost (soft, 1), after_ideal_end_date_cost (soft, 1'000'000), crew_conflict_cost (hard, 1), tag_conflict_cost (soft, 1'000); all flippable, none a reward, all scored by default (default_enabled).