● How to use · Scheduling
Flight crew scheduling
Staff every seat on every flight with crew who hold the right qualification, without overlaps and with feasible connections.
What it decides
For every crew seat on every flight, the solver picks a crew member.
Minimal example
from datetime import datetime, timedelta
from optimaru import flight_crew_scheduling as fc
from optimaru.flight_crew_scheduling.models import (
AirportModel, EmployeeModel, FlightAssignmentModel, FlightCrewScheduleModel, FlightModel,
)
out = datetime(2026, 1, 5, 8)
flights = [
FlightModel(flight_number="OUT", departure_airport="ICN", departure_utc_date_time=out,
arrival_airport="NRT", arrival_utc_date_time=out + timedelta(hours=2)),
FlightModel(flight_number="BACK", departure_airport="NRT",
departure_utc_date_time=out + timedelta(hours=5),
arrival_airport="ICN", arrival_utc_date_time=out + timedelta(hours=7)),
]
problem = FlightCrewScheduleModel(
airports=[AirportModel(code="ICN"), AirportModel(code="NRT")],
employees=[EmployeeModel(id="P1", home_airport="ICN", skills=["Pilot"])],
flights=flights,
flight_assignments=[
FlightAssignmentModel(id=f"A{i}", flight=f.flight_number, required_skill="Pilot")
for i, f in enumerate(flights)
],
)
result = fc.solve(problem, time_limit_seconds=2.0, random_seed=42)
print(result.score_hard, result.score_soft)
print({a.id: a.employee for a in result.flight_assignments}) The same use case as a Jupyter notebook, with charts and saved outputs: examples/flight-crew-scheduling.ipynb ↗
Input parameters
AirportModel
| Field | Meaning |
|---|
code required EmployeeModel
| Field | Meaning |
|---|
id required home_ airport required skills unavailable_ days FlightModel
| Field | Meaning |
|---|
flight_ number required departure_ airport required departure_ utc_ date_ time required datetime is read as UTC.arrival_ airport required arrival_ utc_ date_ time required FlightAssignmentModel
| Field | Meaning |
|---|
id required flight required flight_number of the flight.required_ skill pinned employee: it counts in the score but never moves.FlightCrewScheduleModel
| Field | Meaning |
|---|
airports required employees required flights required flight_ assignments required Solve parameters
What you pass to the solve call. Time limit, seed and parallel count are here.
| Parameter | Default | Meaning |
|---|---|---|
time_ | None | Search budget in seconds, from 0 to 1e9. Left unset, it is the config's spent_limit_seconds, 30 by default. |
random_ | None | Seed for the search. Left unset, it is the config's value, 0 by default. |
parallel_ | None | Independent parallel starts. Each gets its own seed and the full budget, and the best result wins. Left unset, it is the config's value, 1 by default. |
stop_ | False | Stop as soon as hard 0 is reached. |
on_ | None | Callback run on each new best solution. If it raises, the solve stops and raises the same exception. |
config | None | A SolverConfig as the base configuration. Keyword arguments here override it for this solve only; the object you pass is not changed. |
constraints | None | Which constraints to score, and how. Left unset, the defaults apply. |
All search options (20)
Set these on a SolverConfig and pass it as config=.
| Parameter | Default | Meaning |
|---|---|---|
best_ | — | Stop early once the best score reaches this value. By default it never fires. |
change_ | 0.75 | Relative share of change moves. 0 disables them. |
full_ | False | Check every incremental score against a full recompute. Slow; for debugging. |
late_ | 0 | Late-acceptance history length. 0 picks it from the instance size. |
on_ | None | Callback run on each new best solution. If it raises, the solve stops and raises the same exception. |
parallel_ | 1 | Independent parallel starts, each with its own seed and the full budget. The best one wins. |
random_ | 0 | Seed for the search. |
ruin_ | True | Run adaptive ruin-and-recreate kicks when the search stagnates. |
ruin_ | 60 | Absolute cap on entities removed per kick. |
ruin_ | 0.3 | Largest share of the solution one kick removes. |
ruin_ | 0.1 | Smallest share of the solution one kick removes. |
ruin_ | 0.8 | How fast operator weights adapt. |
ruin_ | 5000 | Hill-climbing moves that polish each kick. Not counted against step_count_limit. |
ruin_ | [33.0, 9.0, 3.0, 0.0] | Operator rewards for a new best, a better, an accepted and a rejected result. |
ruin_ | 5000 | Steps without a new best before a kick. |
spent_ | 30.0 | Time budget in seconds, from 0 to 1e9. |
step_ | 0 | Stop after this many steps. 0 means no limit. |
swap_ | 0.25 | Relative share of swap moves. 0 disables them. |
unimproved_ | 0.0 | Stop after this many seconds without a new best. 0 means no limit. |
unimproved_ | 0 | Stop after this many steps without a new best. 0 means no limit. |
What comes back
solve takes the model, or a dict of the same shape, and returns the solved model.
FlightAssignmentModel
| Field | Meaning |
|---|
employee None means unassigned.FlightCrewScheduleModel
| Field | Meaning |
|---|
score_ hard score_ soft Constraints
Pick them by calling their classes from optimaru.flight_crew_scheduling.constraints, such as RequiredSkillCost(). Only what you pass is scored; pass nothing to keep the defaults. A list may name a constraint more than once, and each pick is scored on its own. Each one takes these parameters:
| Parameter | Default | Meaning |
|---|---|---|
weight | None | Multiplier on the constraint's cost, in units of the level in effect. Left unset, the default weight below applies. A constraint whose default weight is 0 is off until you give it a weight. |
level | None | "hard" makes the constraint a must and "soft" a preference, as do Level.HARD and Level.SOFT. Left unset, it keeps the level below. This use case has no medium level, so "medium" raises ValueError. A reward refuses "hard", and a fixed level refuses any change; both raise ValueError. |
exponent | 1.0 | Sign-preserving power on the cost, above 0, taken after offset. 2.0 squares it, so concentrated violations cost much more. It applies per unit, such as a vehicle or a day, or to the total of a constraint scored as one sum. |
offset | 0.0 | Subtracted from the cost x before the exponent, per unit or total like the exponent. It is in the cost's own measure: seconds, minutes, a count and so on. Any finite number of either sign, keyword only. clip decides what happens below it. |
clip | True | True makes offset a threshold: only the part beyond it counts, max(0, x - offset) ** exponent, so a cost at or below it adds nothing. False takes the literal (x - offset) ** exponent, sign kept: a unit below the offset counts negative, as a reward, even one whose cost is 0. On a level that counts toward hard, clip=False with a non-zero offset raises ValueError, since hard 0 must mean no violation. Keyword only. |
This continues the minimal example above.
from optimaru.flight_crew_scheduling.constraints import (
EmployeeUnavailabilityCost, FlightConflictCost, RequiredSkillCost, get_constraints,
)
picked = get_constraints([
RequiredSkillCost(), FlightConflictCost(), EmployeeUnavailabilityCost(level="soft"),
])
custom = fc.solve(problem, time_limit_seconds=2.0, random_seed=42, constraints=picked)
print(custom.score_hard, custom.score_soft) | Name | Level | Default weight | What it does |
|---|---|---|---|
required_ | Hard | 100 | A crew member on a seat without the skill it requires. |
flight_ | Hard | 10 | Pairs of one person's assignments that overlap in time. |
transfer_ | Hard | 1 | An arrival airport that differs from the person's next departure airport. |
employee_ | Hard | 10 | An assignment touching an unavailable date, from departure date to arrival date. |
first_ | Soft | 1000 | A person's first assignment not leaving from home_airport. |
last_ | Soft | 1000 | A person's last assignment not ending at home_airport. |
Starting from an existing solution
This needs the latest release: pip install -U optimaru.
with_initial_solution(problem, solution) returns a copy of problem whose search starts from solution, the model a solve returned or that model as a JSON dict.
This continues the minimal example above.
seeded = fc.with_initial_solution(problem, result.model_dump(mode="json"))
again = fc.solve(seeded, time_limit_seconds=2.0, random_seed=43)
print(again.score_hard, again.score_soft) - Assignments are matched by id.
- A complete solution skips construction: the search starts exactly from it. A partial one keeps what it gives, and only the assignments it leaves out are constructed.
- With
time_limit_seconds=0the solve stops at once, so a complete solution comes back as it went in. Use the time limit for this:step_count_limit = 0means no limit. - Pinned assignments keep their employee on
problem, whatever the solution says. - Unknown ids raise
ValueError.
Exceptions and limits
- There is no rest-time or duty-hour rule. The hard rules are skills, overlaps, connections and unavailable dates.