Skip to content

optimaru.flight_crew_scheduling

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

optimaru.flight_crew_scheduling

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

The flight-crew-scheduling use case: an assignment-shaped problem that picks a crew member (employee) for every crew seat of a flight (FlightAssignment).

Constraints, at the default weights: hard 1. required_skill_cost -100 per assignment without the skill hard 2. flight_conflict_cost -10 per time-overlapping assignment pair of one crew member hard 3. transfer_between_two_flights_cost -1 per pair of departure-consecutive assignments whose airports do not connect (arrival airport != next departure airport) hard 4. employee_unavailability_cost -10 per assignment of a crew member unavailable on the flight date soft 5. first_assignment_not_departing_from_home_cost -1000 when the first assignment departs from an airport other than home soft 6. last_assignment_not_arriving_at_home_cost -1000 when the last assignment arrives at an airport other than home The weights are the C++ components' defaults; change one through a constraint selection, e.g. solve(schedule, constraints=[..., RequiredSkillCost(weight=500)]) (see optimaru.flight_crew_scheduling.constraints). constraint_info() lists every constraint with its default level and weight.

The high-level entry point is solve. It takes a pydantic model or a dict and returns the solved model::

import optimaru.flight_crew_scheduling as fc

result = fc.solve(problem_dict, time_limit_seconds=10.0, random_seed=42)
print(result.score_hard, result.score_soft)

There is also a low-level path that builds engine objects (FlightCrewSchedule) directly and uses Solver. The pydantic mirror is in optimaru.flight_crew_scheduling.models.

optimaru.flight_crew_scheduling.models

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

Mirrors _core's Airport/Employee/Flight/FlightAssignment/FlightCrewSchedule and SolverConfig 1:1, but references are identifiers instead of indices (airport code, flight flight_number, employee id), times are datetime (naive == UTC) and dates are date. The engine-side units are minute/day indices from the Unix epoch::

from optimaru.flight_crew_scheduling.models import FlightCrewScheduleModel

model = FlightCrewScheduleModel.model_validate(problem_dict)
schedule = model.to_core()                    # pydantic -> engine
solved = FlightCrewScheduleModel.from_core(schedule)  # engine -> pydantic

AirportModel

Bases: StrictModel

An airport. code (IATA) is the identifier.

EmployeeModel

Bases: StrictModel

A crew member (value range). home_airport references an airport code.

FlightModel

Bases: StrictModel

A flight. Times are UTC (a naive datetime is read as UTC).

FlightAssignmentModel

Bases: StrictModel

One crew seat of a flight. employee is the decision variable (None == unassigned; references a crew member id).

FlightCrewScheduleModel

Bases: StrictModel

Solution mirror. score is a read-only result, kept as a separate field.

to_core

to_core() -> _core.FlightCrewSchedule

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

from_core classmethod

from_core(schedule: FlightCrewSchedule) -> FlightCrewScheduleModel

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

SolveConfig

Bases: SolveConfigBase

Serializable mirror of _core.SolverConfig.

late_acceptance_size 0 is automatic: clamp(4 * seats, 400, 3200). A positive value is used as it is.

FlightCrewScheduleRequest

Bases: SolveRequest

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

datetime_to_minutes

datetime_to_minutes(value: datetime) -> int

naive (=UTC) or tz-aware datetime -> minutes from the epoch.

minutes_to_datetime

minutes_to_datetime(minutes: int) -> datetime

minutes from the epoch -> naive (=UTC) datetime.

with_initial_solution

with_initial_solution(problem, solution)

Return a copy of problem whose search starts from solution.

solution is what a solve returns: a FlightCrewScheduleModel, or a plain dict of that shape (the JSON the API returned). Assignments are matched by id. An assignment 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 assignments keep their employee on problem, whatever solution says.

Raises ValueError naming the assignment for an unknown or repeated id and for an unknown employee id (the engine does not range-check).

solve_request

solve_request(request: FlightCrewScheduleRequest, *, constraints=None) -> FlightCrewScheduleModel

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.

parameter_uses

parameter_uses(schedule: FlightCrewScheduleModel) -> list[ParameterUse]

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

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

optimaru.flight_crew_scheduling.constraints

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

The default path (fcs.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.flight_crew_scheduling as fcs
from optimaru.flight_crew_scheduling.constraints import (
    FlightConflictCost, RequiredSkillCost, get_constraints,
)

fcs.solve(schedule, constraints=get_constraints())          # the defaults as-is
fcs.solve(schedule, constraints=[                           # picked
    FlightConflictCost(), RequiredSkillCost(weight=500),
])

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

Every spec takes five knobs:

  • weight linear multiplier on the constraint cost. None = the component default (RequiredSkillCost 100, FlightConflictCost 10, TransferBetweenTwoFlightsCost 1, EmployeeUnavailabilityCost 10, the two home-airport constraints 1000); fcs.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 per employee: weight * sign(c) * |c| ** exponent. 2.0 = squared, so concentrated violations grow much costlier.
  • offset (keyword) shifts that shaping per employee; 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 an employee below the offset — an idle one (cost 0) included — lowers the penalty. With an offset it is refused on hard (the four hard constraints 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 and the picks add up. A conflict costs its weight, and every conflict an employee has beyond the first costs its square on top::

fcs.solve(schedule, constraints=[
    *get_constraints(),
    FlightConflictCost(weight=10, exponent=2, offset=1),
])

fcs.constraint_costs(schedule, picks) keys the second pick "flight_conflict_cost#2".

Names (name) are the C++ component names in snake_case (RequiredSkillCost -> required_skill_cost). The core derives them mechanically, so there is no hand-maintained alias table — check them with fcs.list_constraints(). Module-level instance names use the same snake_case, so they match the strings list_constraints() prints.

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.

RequiredSkillCost dataclass

Bases: Constraint

Crew assignments lacking the skill the seat requires. Default: hard, weight 100.

The heaviest hard constraint — a crew member who cannot take the seat is worse than any scheduling inconvenience.

FlightConflictCost dataclass

Bases: Constraint

Pairs of the same crew member's assignments that overlap in time. Default: hard, weight 10.

The plain sum over pairs within one itinerary, so the exact delta an assignment brings in or out is its overlap count with the other members.

TransferBetweenTwoFlightsCost dataclass

Bases: Constraint

Arrival airport differing from the next departure airport. Default: hard, weight 1.

Someone has to move the crew in between by plane or car. "Next" is by departure time — assignments with the same departure time do not start a pair, and all ties at the later end count.

EmployeeUnavailabilityCost dataclass

Bases: Constraint

Assignments touching a date the crew member is unavailable. Default: hard, weight 10.

Caught if any calendar date the flight spans, from departure date to arrival date inclusive, is unavailable.

FirstAssignmentNotDepartingFromHomeCost dataclass

Bases: Constraint

The first assignment not departing from the home airport. Default: soft, weight 1000.

It means getting there on one's own time. All ties at the earliest departure time count.

LastAssignmentNotArrivingAtHomeCost dataclass

Bases: Constraint

The last assignment not arriving at the home airport. Default: soft, weight 1000.

The roster ends with the crew member stuck away from home. All ties at the latest departure time count.

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([FlightConflictCost(), RequiredSkillCost(weight=500)])

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 fcs.constraint_costs(schedule) returns: per constraint, the raw cost of each employee (before weight, exponent, offset and level rounding). Fetch it once and rescore with different weights without re-solving::

raw = fcs.constraint_costs(schedule)
score(raw)                     # default set
score(raw, [FlightConflictCost(), RequiredSkillCost(weight=500)])
score(raw, [FlightConflictCost(), FlightConflictCost(exponent=2, offset=1)])

No solver and no search are involved. The arithmetic matches the engine — each employee contributes weight * shape(cost, exponent, offset, clip) and hard contributions are rounded per employee before summing (the same order as the engine; 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.flight_crew_scheduling._core

Type stubs for optimaru.flight_crew_scheduling._core — the flight-crew-scheduling C++ solver.

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

Domain: a assignment-shaped problem picking a crew member (employee index) for every crew seat of a flight (FlightAssignment). Airport/employee/flight references are all list indices (the pydantic mirror optimaru.flight_crew_scheduling.models uses code/id string references).

Time unit: minutes from a reference epoch (Unix in the model). Dates are day indices obtained as floor(minutes / 1440).

Score convention: hard/soft, at the default weights — the C++ components' defaults (constraint_info()): hard 1. required_skill_cost -100 per assignment without the skill hard 2. flight_conflict_cost -10 per overlapping assignment pair of one crew member hard 3. transfer_between_two_flights_cost -1 per disconnected consecutive assignment pair hard 4. employee_unavailability_cost -10 per assignment on an unavailable day soft 5. first_assignment_not_departing_from_home_cost -1000 soft 6. last_assignment_not_arriving_at_home_cost -1000

Score

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

is_feasible

is_feasible() -> bool

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

Airport

Problem fact: an airport. Other objects reference it by index into this list.

Employee

Problem fact (value range): a crew member.

home_airport instance-attribute

home_airport: int

Index into the airports list.

unavailable_days instance-attribute

unavailable_days: set[int]

Set of day indices of unavailable days (floor(minutes / 1440)).

Flight

Problem fact: a flight. Times are minutes from the reference epoch (UTC).

FlightAssignment

One crew seat of a flight. employee is the decision variable (-1 == unassigned), written by the solver.

employee instance-attribute

employee: int

Index into the employees list; -1 == unassigned.

pinned instance-attribute

pinned: bool

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

FlightCrewSchedule

Problem and solution in one object. solve changes the flight_assignments' employee and score in place.

Note: list attributes such as flight_assignments return copies, so use set_assignment to change assignments.

assignment

assignment() -> list[int]

Current employee index per seat (-1 == unassigned).

set_assignment

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

Bulk-write the decision variable (length == number of seats).

SolverConfig

late_acceptance_size instance-attribute

late_acceptance_size: int

0 = automatic: clamp(4 * seats, 400, 3200).

best_score_limit instance-attribute

best_score_limit: tuple[int, float]

Stop early at or above this score. (0, -inf) stops at the first feasible.

Solver

solve

solve(schedule: FlightCrewSchedule) -> None

Solves in place: fills the employee assignments and score. Pinned seats are kept.

solve_with_constraints

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

Score the same solve with a caller-chosen constraint set (see optimaru.flight_crew_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: FlightCrewSchedule) -> Score

Full recalculation (also stored in schedule.score).

list_constraints

list_constraints() -> list[str]

Constraint names scored by this domain (default assembly order, snake_case): required_skill_cost, flight_conflict_cost, transfer_between_two_flights_cost, employee_unavailability_cost, first_assignment_not_departing_from_home_cost, last_assignment_not_arriving_at_home_cost. The same names optimaru.flight_crew_scheduling.constraints uses.

constraint_costs

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

Raw per-employee cost of every constraint, before weight/exponent/offset/level: {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}}, one cost per employee (every employee is evaluated, an idle one included). 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.flight_crew_scheduling.constraints.score() turns it into a score.

constraint_info

constraint_info() -> list[ConstraintInfo]

The constraint catalog, in list_constraints() order: required_skill_cost (hard, 100), flight_conflict_cost (hard, 10), transfer_between_two_flights_cost (hard, 1), employee_unavailability_cost (hard, 10), first_assignment_not_departing_from_home_cost (soft, 1000), last_assignment_not_arriving_at_home_cost (soft, 1000); all flippable, none a reward, all scored by default (default_enabled).