Use cases¶
Each use case is an independent problem built on the engine in
core/optimaru/ and shipped as a subpackage of
optimaru. This directory holds one guide per use case. Competing solvers
(OR-Tools CP-SAT / Routing) never live in the package; they are in
benchmarks/.
| Use case (guide) | Python package |
|---|---|
| assembly-line-balancing | optimaru.assembly_line_balancing |
| bed-allocation | optimaru.bed_allocation |
| bin-packing | optimaru.bin_packing |
| conference-scheduling | optimaru.conference_scheduling |
| employee-scheduling | optimaru.employee_scheduling |
| facility-location | optimaru.facility_location |
| flight-crew-scheduling | optimaru.flight_crew_scheduling |
| food-packaging | optimaru.food_packaging |
| knapsack | optimaru.knapsack |
| maintenance-scheduling | optimaru.maintenance_scheduling |
| max-cut | optimaru.max_cut |
| meeting-scheduling | optimaru.meeting_scheduling |
| order-picking | optimaru.order_picking |
| pickup-delivery | optimaru.pickup_delivery |
| project-job-scheduling | optimaru.project_job_scheduling |
| quadratic-assignment | optimaru.quadratic_assignment |
| school-timetabling | optimaru.school_timetabling |
| semiconductor-scheduling | optimaru.semiconductor_scheduling |
| sports-league-scheduling | optimaru.sports_league_scheduling |
| task-assigning | optimaru.task_assigning |
| tournament-scheduling | optimaru.tournament_scheduling |
| vehicle-routing | optimaru.vehicle_routing |
Every use case is a C++ domain on the optimaru engine with a pybind11 Python
package; they all share one constraint contract (below). Six of them
(assembly-line-balancing, bin-packing, knapsack, max-cut, quadratic-assignment
and semiconductor-scheduling) also carry a pure-Python reference scorer as
tests/<use case>/reference_<use case>.py, an independent oracle the C++ costs are
tested against.
One way to solve¶
Every use case has the same two entry points: optimaru.<use case>.solve for
a problem in Python, and optimaru.<use case>.solve_request for a pydantic
request (JSON in, JSON out). The request carries the settings of the solve
under the names of solve's keywords, so the two say the same thing in the
same words.
solve takes the problem and the settings as keywords:
solved = uc.solve(
problem,
time_limit_seconds=5.0, # every argument below is optional
random_seed=42,
parallel_solver_count=1,
stop_at_first_feasible=False, # stop as soon as hard 0 is reached
full_assert=False, # check every incremental score (slow; for debugging)
on_new_best=None, # called with (step, score) on every new best
config=None, # a SolverConfig; the keywords above override a copy of it
constraints=None, # constraint picks; None = the default set
)
It returns the solved problem, and the score is on it.
- A problem built from the compiled classes (
optimaru.<use case>.<Problem>) is solved in place and returned, with its score insolved.score. - A pydantic problem model from
optimaru.<use case>.modelsis not changed:solvereturns a new, solved model with its score fields (score_hard,score_soft, and one per further level the use case has). The model you passed stays the problem it was, so it can be solved again or handed towith_initial_solution(problem, solved). (calculate_score(model), where a use case accepts a model there, is the one call that writes into it: it fills in the model's score fields.)
parallel_solver_count=N runs N independent starts, start i with
random_seed + i, and returns the best of them. A solve with constraints=...
runs one start, except in vehicle routing and pickup and delivery, where every
start scores on its own copy of the picks. on_new_best reports the first
start only, so the returned
score can be better than the last one it was called with. A start that reaches
a target (stop_at_first_feasible, best_score_limit) stops the others: they
hand over their best so far, and the best of all starts is returned. Which start
gets there first depends on the threads, so with a target and more than one
start the same seed can give a different solution from run to run.
solve_request takes a request model, optimaru.<use case>.models.<Name>Request,
and the constraint selection:
request = uc.models.KnapsackRequest( # each use case names its own request
model_input=problem_model, # the pydantic problem
time_limit_seconds=5.0, # the fields below are optional and mean
random_seed=42, # what solve's keywords of the same name do
parallel_solver_count=1,
stop_at_first_feasible=False,
full_assert=False,
solver_parameters={}, # further SolverConfig fields by name
)
solved = uc.solve_request(request, constraints=None)
Every request has these fields (the shared base is optimaru._models.SolveRequest).
Earlier versions named two of them differently, and those names are still
accepted, in JSON, as keywords and as attributes: timelimit for
time_limit_seconds and num_workers for parallel_solver_count. The request
is not changed. What comes back:
- In 17 use cases the request wraps the problem model as
model_input, andsolve_requestreturns whatsolvereturns for that model: a new, solved model. - Employee scheduling, order picking, pickup & delivery and vehicle routing
answer with a response model of their own (
ScheduleSolution,OrderPickingResponse,PdpSolution,RouteSolution). Theirsolve()takes the compiled problem only. Order picking's request holdstrolleysandordersitself instead of amodel_input. An employee scheduling request also hassettings, the search options of that use case; itssettings.random_seedandsettings.stop_at_first_feasibleare the request's own fields under another name. - School timetabling's
solvetakes and returns dicts (aTimetableProblemin, aTimetableout) and has three more keywords,mode,weightsandinitial_solution. Its request,TimetableRequest, holds the problem as aTimetableProblemModeland those three as fields, andsolve_requestreturns aTimetableResultModel.
Solver(config).solve(problem) and solve_with_constraints(problem, picks)
are the same solves one level down, without the keyword conveniences.
Choosing the acceptance rule¶
Pickup and delivery, quadratic assignment, semiconductor scheduling and
vehicle routing let you choose the rule local search accepts a move by, on
SolverConfig. The attributes and their defaults are the same in the four:
acceptor_type |
Its parameters | Default |
|---|---|---|
LATE_ACCEPTANCE |
late_acceptance_size |
0 = the use case's automatic size |
HILL_CLIMBING |
none | |
ENTITY_TABU |
entity_tabu_size: steps a moved entity stays tabu |
7 |
SIMULATED_ANNEALING |
simulated_annealing_starting_temperature (hard, soft), cooling to 0 over the solve; simulated_annealing_temperature_fraction |
(0, 0) = automatic: hard 0, soft = the fraction (0.01) of the start's soft level, at least 1. The soft level alone: the medium level (unassigned visits in vehicle routing, unassigned requests in pickup and delivery) does not count. Give the temperature yourself when your picks can make the soft level positive (a reward, or an offset without clip) or larger than the medium level's unit |
GREAT_DELUGE |
great_deluge_water_level_step (hard, soft): how much the water level, which starts at the start's score, rises per step |
(0, 0): the level stays at the start's score |
STEP_COUNTING_HILL_CLIMBING |
step_counting_hill_climbing_size: the bar is reset to the current score every this many steps |
400 |
RECORD_TO_RECORD_TRAVEL |
record_to_record_start_gap, record_to_record_end_gap: the gap below the best score that is still accepted, as a fraction of the start's soft score |
0.02, shrinking to 0.0 over the solve (an end gap above the start gap is the gap throughout) |
The default rule is late acceptance, and simulated annealing in semiconductor scheduling. In vehicle routing and pickup and delivery an amount you give yourself (a starting temperature, a water level step) is on the scale the search compares in, where the medium level counts 10^9 per unit: only the automatic temperature leaves the medium level out. The record-to-record gaps are fractions of that same scale, so a start that leaves work unassigned widens them. A great deluge needs a step chosen for the instance: at (0, 0) it takes every move that keeps the score at or above the start's and never tightens.
Late acceptance in stages¶
A late acceptance history is a trade: a short one converges fast, a long one
finds more and needs longer. In bed allocation, facility location, food packaging,
knapsack, maintenance scheduling, max-cut, quadratic assignment and sports league
scheduling the search does not stay with one length. late_acceptance_size
is the history of the first stage. Once that stage has converged and no new
best has come for a while, late acceptance starts over from the start's score
with the history doubled, then doubled again, as long as the next stage still
fits in the time limit (or the step limit; a stage is taken to last twice as
long as the one before). The best solution is kept throughout, so a solve is
never worse for a later stage, and a small instance uses a budget that one
short history would leave idle. A
history stops growing at 2^20 entries (16 MB per start); from there a stage
starts over with that length. A stage walks below the best for a while and
does not know the unimproved_* limits: one shorter than a stage ends the
solve inside it, with the best solution so far.
A use case can also draw its own macro moves less often from the first
restart on (AcceptanceSettings::later_stage_custom_move_share): a later stage
takes worse solutions for a long while, and moves that each make a pass over
the whole solution would take the steps of the moves that polish. Facility
location does, at a tenth of custom_move_probability.
Only a solve that the construction starts runs in stages. One that starts from
a solution you give (with_initial_solution, a request's initial_solution),
also one that places only a part and leaves the rest to the construction,
keeps the one history of late_acceptance_size and searches with the
ruin-and-recreate kicks, as every solve did before the stages: the start's
score is then no lower than where the search stands, so starting over from it
would loosen nothing and take the place of a kick. In 0.5.0 such a solve ran
in stages too, and one whose improvements come from the kicks could return its
start whatever the budget.
Whether a stage fits is judged on how far the solve is: the larger of the time used over the time limit and the steps used over the step limit. So with a time limit, which stage a solve reaches depends on the clock. A seeded, step-limited solve repeats as long as the step fraction is the larger one; give it a time limit generous enough for the steps.
Solving on the optimaru API¶
The optimaru API is the Enterprise edition of the engine: the same engine, run as a
hosted service. The body of its solve request is the Python call (the first argument and
the keywords of solve or solve_request, as JSON), so a program that uses this
package moves onto it with one setting, an API key. Give it in the environment:
export OPTIMARU_API_KEY=om_live_...
or in code:
import optimaru
optimaru.use_api("om_live_...")
With a key, solve(model, ...) and solve_request(request, ...) send the problem to
the API, wait for the solve job and return what they return on this machine: a new
solved model, or the response model. The rest of the program stays as it is. Without a
key nothing is sent.
OPTIMARU_API_URL, oroptimaru.use_api(key, url=...), names another API thanhttps://app.optimaru.com. It must be an https URL (http is accepted for localhost).optimaru.use_api()without a key readsOPTIMARU_API_KEY, andoptimaru.use_local()solves on this machine again, whatever the environment says.- What cannot be sent is refused instead of being solved here without notice: a problem
built from the compiled classes (it is solved in place, which a result that comes back
as JSON cannot do; pass its model,
Model.from_core(problem), and use the model that comes back), thesolve(problem)of the four use cases whose pydantic layer is a whole request (vehicle routing, pickup and delivery, order picking, employee scheduling: callsolve_request), a callback (on_new_best, employee scheduling'sselect) and a non-finite number. - School timetabling goes to the API like the others. Its
solve(problem, ...)takes a dict, so it is sent as theTimetableRequestthatsolve_requesttakes (the problem, the keywords, andconfigas the request's fields andsolver_parameters), and the result comes back as the dict a local solve returns. - The setting moves
solveandsolve_request. The compiledSolverclass (Solver(config).solve(problem),solve_with_constraints) is the engine itself and always runs on this machine. configtravels as theSolverConfigfields that differ from the defaults andconstraintsas the picks in their order, so a solve with the same seed and a step limit gives the same result there as here on the same engine version. Asolvekeyword or aSolverConfigfield left at its default takes the default of the engine the API runs; a request carries all its own fields.use_api()applies to the process that calls it. Worker processes that start fresh (spawn, forkserver: the default on macOS and Windows, and on Linux from Python 3.14) need their own call; the environment variable reaches them by itself.- What the API refuses or fails at raises
optimaru.ApiError: the HTTPstatus, the API's errorcode("INVALID_CREDENTIALS","PLAN_LIMIT_EXCEEDED","VALIDATION_ERROR", ...;"JOB_FAILED"carries the engine's own message for an input it refused), itsdetail, andretry_afterwhen the API said how long to wait. - A solve is a job on the API that the call waits for, from when the job is created, for
at most twice its time limit (times its parallel starts, for a request) and ten minutes
more; then it is cancelled and
ApiErrorsays so ("JOB_TIMEOUT"). A look at the job that fails for a reason that passes (the network, a 5xx, a 408, a 429) is tried again for a tenth of that wait, and at least a minute, but not past the wait (give or take one request); the read of the result is tried again the same way. Creating the job is not tried again, since that could solve it twice. Interrupting a solve (Ctrl-C) once its job exists cancels the job. - The problem and the settings leave the machine, over https, to the API; the first
solve sent there is logged at INFO on the
optimarulogger. No redirect is followed, so the key goes to that API only.calculate_score,constraint_costsand the other helpers keep running here. - A dict in what comes back (routes by vehicle, an assignment by location) has the same entries as here, possibly in another order: the API keeps a JSON object's keys unordered. Read it by key.
- The API has limits of its own: how long one job may run, how many parallel starts it
may take, and what the plan of the key allows. Past one it answers with an
ApiErrorthat says which. - The API runs a released engine. A
SolverConfigfield or a model field that a newer source checkout has and the API's engine does not is refused there by its name.
The request the API takes, endpoint by endpoint, is its REST reference; this section is
what the package does with it. A new use case decides where it solves when it is added:
optimaru/_api.py has one decorator for each answer (see
Layout of a use case).
Constraints: names and knobs¶
Every constraint is one named component, <Subject>Cost in C++ and Python and
<subject>_cost as its Python name (vehicle_capacity_cost; the C++ registry
name is the camelCase vehicleCapacityCost). Its raw cost is 0 when nothing
is violated and positive otherwise; a reward (a quantity to maximize, such
as knapsack's selected_value_cost) has a raw cost <= 0.
A selection is a list of picks, written as class calls
([VehicleCapacityCost(), TravelTimeCost(weight=10)]). Each pick sets five
knobs and nothing else:
weight—Nonekeeps the default weight, in units of the constraint's level.level—Nonekeeps the default level. Otherwise aLevelfrom the package'sconstraintsmodule, or its name:Level.HARD/"hard",Level.MEDIUM/"medium",Level.SOFT/"soft".mediumneeds a domain with a medium level. A reward refuses"hard", and a structural constraint (level_flippablefalse, e.g. school timetabling'sfixed_slots_cost) refuses any change of level.exponent—1.0by default,> 0, sign-preserving; applied per unit for a unit constraint and to the single total for a global one, before the weight.offset—0.0by default, any finite number, in the unit of the raw cost; keyword-only. It shifts the shaping at the same granularity asexponent.clip—Trueby default; keyword-only.Truemakes the offset a threshold,sign(x) * max(0, |x| - offset) ** exponent: only the part of a raw costxbeyond the offset counts.Falseis the literal formula, the sign-preserving(x - offset) ** exponent, which is negative (a reward) below the offset and charges every unit the constraint evaluates, a raw 0 included. Each use case's README says which units those are.clip=Falsewith a non-zero offset is refused on hard, and on medium where medium counts toward the hard score (task assigning), because hard 0 must mean no violation:ValueError: constraint 'vehicle_capacity_cost': clip=False with a non-zero offset cannot be hard, because hard 0 must mean no violation; use clip=True (a threshold) or another level. The threshold (clip=True) is allowed on every level.
So TravelTimeCost(offset=10, exponent=3) adds max(0, x - 10)**3 per
vehicle, and the soft TravelTimeCost(offset=10, exponent=3, clip=False) adds
(x - 10)**3 per vehicle, an idle one included. Both formulas apply per unit,
not to the total. With offset=0 both modes are the plain x ** exponent. A
weight of 0 contributes exactly 0 at any exponent and offset. A unit constraint
picked at weight 0 is also left out of the moves, so it costs the search no
time, and constraint_costs() still reports its raw cost. (A global constraint
is left out only if it declares it can be, and a constraint that school
timetabling or employee scheduling compiles into a shared group is still
evaluated with that group.)
A negative offset with clip=True is a fixed charge per unit in use:
TravelTimeCost(offset=-60) adds x + 60 for a vehicle that drives and 0 for
an idle one. That jump at 0 needs the raw cost exactly, so the engine recomputes
such a constraint for every unit a move changes instead of updating it by the
difference. The score is the same, but the solve is slower: in vehicle routing
it took about half as many steps per second as TravelTimeCost() on 100 to
1,000 visits. A positive threshold and clip=False are not recomputed this
way.
A constraint may be picked several times. Each pick is its own instance with its
own knobs (its level included) and, where the constraint has domain parameters,
its own parameters. The instances are scored independently and add up, so
[TravelTimeCost(exponent=2), TravelTimeCost(exponent=3)] is x**2 + x**3, and
two identical picks simply count twice. A further pick of a constraint without
domain parameters usually reuses the raw cost the engine computed for the first
one and only shapes it again, so it costs much less than a new constraint.
An empty list is an error, and so is an
unknown name. Each package's constraints module also holds ready-made default
instances under the snake-case names (vehicle_capacity_cost is
VehicleCapacityCost()); the docs and examples use the class calls.
Some domains also have a medium level between hard and soft (unassigned
visits, stays, requests, tasks, ...). Any flippable constraint may be moved onto
it, and a weight is in units of the level in effect. The domain declares once how
medium folds into the engine's hard/soft score (medium_fold on every
constraint_costs() entry). Where it folds below hard (task assigning), medium is
whole numbers like hard: each unit's contribution is rounded, so a small fractional
weight can round to nothing, and a reward refuses "medium".
Defaults are declared once, in C++ (kDefaultWeight / kDefaultLevel on the
component). Python reads them from <package>.constraint_info(), one
ConstraintInfo row per constraint with the fields name, default_level,
default_weight, level_flippable, reward and default_enabled.
list_constraints()lists the default set. Employee-scheduling lists all 30 constraints its factory accepts; its defaults are thedefault_enabledrows.constraint_costs(solution, constraints=None)reports every selected constraint's raw costs as{key: {costs, weight, exponent, offset, clip, global, level, reward, level_flippable, name, label, default_weight, default_level}}(weight/level/exponent/offset/clipare the pick's knobs,default_*whatNonemeans). The key of the first pick of a name is the name, the k-th isname#k, in pick order; a scoped constraint also lists the units it evaluates asunits, and a domain with a medium level addsmedium_fold.constraints.score(costs, picks)re-prices them in pure Python with the engine's arithmetic.
Parameters and their costs¶
Many input fields act only through a cost: a vehicle's max_end_time matters only
because vehicle_max_end_time_cost charges the seconds past it, and a worker's
unavailable_dates only because employee_unavailability_cost charges a shift on one
of them. A selection that leaves such a cost out would not score the field at all: at
most an insertion heuristic still steers by it, and nothing keeps a move from breaking it. So a request that sets one of these fields away from its default, while the
effective selection holds none of the costs that read it, is refused with
ValueError. The message names the field, where it is set, and the costs to add:
vehicle V1 sets max_end_time, but the constraints leave out vehicle_max_end_time_cost,
the cost that scores it: add one, or leave max_end_time at its default (0)
- The effective selection is the one the solve scores: the defaults when
constraintsis None, the picks otherwise (employee scheduling: the request'sconstraints; school timetabling: theconstraints=picks, while the fast path withweights=scores every cost). A pick at weight 0 counts: it is a choice the caller made, not an omission. So does a cost the defaults hold at weight 0 (an opt-in objective): pickup-delivery'sorder_timeis accepted with the defaults althoughsquared_order_age_costweighs nothing there, as the owner set the rule ("a default set that includes the cost changes nothing for default requests"); give that cost a weight to useorder_time. Where several costs read one field, any one of them is enough. - Checked where the input is the JSON model:
solve_request, andsolve()given the pydantic model (or school timetabling's problem dict). A compiled problem is solved as it is given. A pick that the engine refuses (an unknown name, a bad knob) is reported for what it is before the parameter check. With an API key set the request is sent as it is and checked where it is solved, by a server on this release (school timetabling also checks before sending). - Not checked: required fields (they have no unset state); fields that shape times,
places or quantities every cost reads (durations, dates, locations, service times,
start times); rules the engine enforces whatever the selection (school timetabling's
fixed slots and parallel groups, max cut's fixed partition, semiconductor scheduling's
decoder rules, routing's forbidden visits and requests, which are always on); fields
with an effect besides their cost (routing profile
distancesand visitdemand, which the solution reports as driving meters and load; school timetabling'srequired_room_type, which the room assignment reads; semiconductor scheduling's lotpriorityand optionpreference_cost, which the decoder's dispatch order and default machine read); and a field left at a default that already means something (pickup-deliverymax_stops=20, school timetabling'smax_periods_per_day=6): only a value other than the default is checked, so a default limit without its cost is still only steered toward by the insertion heuristics, not scored. A value that switches something off, such as a tag list emptied of all but one tag, is still a value other than the default: drop the field, or keep its cost at weight 0.
The fields each use case checks (models.parameter_uses(model) lists the ones an input sets):
| Use case | Field (default) | Cost(s) |
|---|---|---|
| assembly line balancing | precedences ([]) |
task_precedence_cost |
max_stations (None) |
max_stations_cost |
|
same_station_groups ([]) |
same_station_groups_cost |
|
different_station_pairs ([]) |
different_station_pairs_cost |
|
task min_station (0), max_station (None) |
task_station_bounds_cost |
|
task fixed_station (None) |
fixed_task_stations_cost |
|
task forbidden_stations ([]) |
forbidden_task_stations_cost |
|
| bed allocation | department minimum_age, maximum_age (None) |
department_min_age_cost, department_max_age_cost |
department specialty_to_priority ({}), stay specialty ("") |
department_specialty_cost or department_specialty_priority_cost |
|
room gender_limitation (ANY_GENDER) |
the gender cost of the value set | |
room equipment ([]) |
required_patient_equipment_cost or preferred_patient_equipment_cost |
|
stay patient_required_equipment, patient_preferred_equipment ([]) |
required_patient_equipment_cost, preferred_patient_equipment_cost |
|
stay patient_preferred_maximum_room_capacity (None) |
preferred_max_room_capacity_cost |
|
| bin packing | item color (None) |
color_conflict_cost |
conflicts ([]) |
item_conflict_cost |
|
| conference scheduling | talk speakers, tags, audience_*, content_tags, language ("en"), favorite_count, crowd_control_risk, prerequisite_talks, mutually_exclusive_talks_tags; speaker and room unavailable_timeslots and tag lists; room capacity, talk_types; timeslot tags; minimum_consecutive_talks_pause_in_minutes (30; 0 needs nothing) |
the costs that read each field, listed in _TALK_COSTS, _SPEAKER_COSTS, _ROOM_COSTS and _TIMESLOT_COSTS of conference_scheduling/models.py |
| employee scheduling | shift required_skill ("") |
required_skill_cost |
worker unavailable_dates, undesired_dates, desired_dates ([]) |
employee_unavailability_cost, undesired_day_cost, desired_day_cost |
|
worker desired_shifts ([]) |
desired_shift_cost (opt-in: not in the defaults) |
|
| flight crew scheduling | assignment required_skill ("") |
required_skill_cost |
employee unavailable_days ([]) |
employee_unavailability_cost |
|
| knapsack | resource_capacities, item resource_usage ({}) |
resource_capacity_cost |
mandatory_items, forbidden_items ([]) |
mandatory_items_cost, forbidden_items_cost |
|
item requires ([]) |
item_dependency_cost |
|
selection group min_selected (0), max_selected (None) |
selection_group_bounds_cost |
|
| maintenance scheduling | job min_start_date, max_end_date (None) |
min_start_date_cost, max_end_date_cost |
job ideal_end_date (None) |
before_ideal_end_date_cost or after_ideal_end_date_cost |
|
job tags ([]) |
tag_conflict_cost |
|
| max cut | same_partition_pairs, different_partition_pairs ([]) |
their costs |
min_partition_size, max_partition_size (None) |
partition_size_bounds_cost |
|
| meeting scheduling | room capacity (0) |
room_capacity_cost or larger_room_capacity_cost |
meeting required_attendees, preferred_attendees ([]) |
any of the attendance costs, room_capacity_cost, room_change_cost |
|
| pickup-delivery | vehicle max_travel_time, max_route_duration, max_end_time (0), max_stops (20; 0, no cap, needs nothing), min_load_ratio, fixed_cost, max_route_radius_meters (0), pinned_stops (0) |
the matching vehicle cost, pinned_stops_cost |
request order_time (0), required_vehicle, group (None) |
squared_order_age_cost, required_vehicle_cost, request_group_cost |
|
stop max_end_time (86400) |
max_end_time_cost |
|
profile preferred_requests ([]) |
profile_preferred_request_cost |
|
| project job scheduling | project release_date, critical_path_duration (0) |
project_delay_cost |
resource renewable (True) set to False |
non_renewable_resource_capacity_cost |
|
| quadratic assignment | assignment_costs (None) |
assignment_cost |
fixed_assignments ({}), forbidden_assignments ([]) |
pinned_assignments_cost, forbidden_assignments_cost |
|
facility_demands, location_capacities ({}) |
location_capacity_cost |
|
| school timetabling | teacher and class unavailable, course forbidden_slots ([]) |
disallowed_slot_cost |
teacher max_periods_per_week (None), max_periods_per_day (6) |
teacher_max_periods_cost |
|
teacher max_consecutive_periods (4), preferred_free_days ([]) |
teacher_max_consecutive_periods_cost, teacher_free_day_cost |
|
subject avoided_periods, preferred_periods ([]) |
avoided_period_cost, non_preferred_period_cost |
|
course max_periods_per_day (1), block_periods (0 or 1) |
course_max_periods_per_day_cost, block_adjacency_cost |
|
| semiconductor scheduling | machine minimum_batch_size (1) |
min_batch_size_cost |
lot max_cycle_time (None), operation max_queue_time (None) |
max_cycle_time_cost, max_queue_time_cost |
|
| sports league scheduling | match classic_match, round weekend_or_holiday (False) |
workday_classic_matches_cost |
distance_to_team ([]) |
any of the five hop costs | |
| task assigning | task type required_skills ([]) |
required_skill_cost |
task priority MAJOR or CRITICAL (MINOR) |
major_ / critical_priority_task_end_time_cost |
|
| tournament scheduling | unavailability_penalties ([]) |
team_unavailability_cost |
| vehicle routing | vehicle max_travel_time, max_route_duration, max_end_time, max_stops (0), min_load_ratio, fixed_cost, max_route_radius_meters (0) |
the matching vehicle cost |
visit max_end_time (86400), unassigned_penalty_minutes (-1) |
max_end_time_cost, unassigned_visits_cost |
|
visit group (None), after ([]) |
visit_group_cost, visit_order_cost |
|
profile preferred_visits ([]) |
profile_preferred_visit_cost |
Facility location, food packaging and order picking check nothing: every field a cost
reads there is required. Some fields are read by nothing at all, so no selection can
give them an effect: food packaging's job min_start_time and priority, meeting
scheduling's entire_group_meeting, school timetabling's subject_ids,
homeroom_class_id and grade, and facility location's map corners.
Layout of a use case¶
optimaru/<use case>/
├── __init__.py, models.py, the Python API: solve, pydantic models,
│ constraints.py, _core.pyi constraint specs, extension stubs
└── cpp/
├── bindings.cpp pybind11 module optimaru.<use case>._core
├── CMakeLists.txt core library, demo and C++ tests
├── main.cpp the demo
└── <ns>/ the core library: each header with its source
├── solver.hpp, solver.cpp domain Solver: Config -> engine wiring
├── constraints.hpp default constraint assembly
├── model/
│ └── domain.hpp problem facts, decision variable, Score,
│ SolutionTraits specialization
│ (also here: demo data, travel times)
├── score/
│ ├── score_calculator.* full (reference) score
│ └── incremental_calculator.*
│ tuned incremental score (default path)
├── constraints/*_cost.hpp one plugin component per constraint
└── construct/, search/ only where the use case has its own
(moves/, accept/) construction, moves or acceptor
tests/<use case>/
├── test_*.py pytest suite
└── cpp/<ns>_test.cpp, <ns>_plugin_test.cpp
docs/use-cases/<slug>/ README.md, python.md: its guide
The constraint-spec base every constraints.py builds on is
optimaru/_constraint.py, shared by all use cases.
The two steps the solve() functions share, the keyword overrides on a copy of the
config and the solver call, are in optimaru/_solve.py, and
what several models.py need (the strict model base, the common solver settings, the
checks of with_initial_solution) is in optimaru/_models.py.
Where a solve runs is decided in optimaru/_api.py: a use
case decorates its solve with _api.model_solve("<slug>", <Model>) when the optimaru
API solves it with solve, its solve_request with _api.request_solve("<slug>",
"<Response>") and its solve with _api.compiled_solve when the API solves it with
solve_request (or with _api.solve_by_request(...) when that solve takes a dict that
becomes the request, as in school timetabling). tests/test_api.py fails until a new use
case is in one of the tables of tests/_api_server.py.
Build and test one use case, from the repository root:
cmake -B build -DOPTIMARU_USE_CASES=<use case> && cmake --build build -j
ctest --test-dir build
OPTIMARU_USE_CASES=<use case> uv sync # builds only that extension, in place
uv run pytest -q tests/<use case>
Starting from an existing solution¶
Every use case can start its search from a solution you already have instead of constructing one. Pass what a previous solve returned, as the result model or as its JSON:
from optimaru.vehicle_routing.models import solve_request, with_initial_solution
first = solve_request(request)
better = solve_request(with_initial_solution(request, first))
The contract is the same everywhere:
- A complete solution skips construction: the search starts exactly from it.
- A partial solution keeps what it gives, and only what it leaves out is constructed. Quadratic assignment is the exception: its search only swaps, so it refuses a partial assignment.
- A solve's result is accepted back, even a hard-infeasible one. The exceptions are pickup-delivery, which refuses a route with a broken pickup and dropoff pair, and school timetabling, which refuses a course placed twice at one time.
- Entities are matched by id, never by position. Unknown ids and out-of-range values
raise
ValueError. with_initial_solutionreturns a new problem and leaves its input untouched.- Pinned parts are problem facts. Most use cases keep the problem's value and
ignore what the solution says. Employee scheduling, food packaging,
pickup-delivery, max-cut and school timetabling raise
ValueErrorwhen the solution contradicts them. - A seed is used once: a result edited and solved again starts from construction
unless you pass it through
with_initial_solutionagain.
School timetabling takes dicts, so it uses a keyword instead:
solve(problem, initial_solution=previous). Each use case's README lists its
exceptions. To stop right after the start, use a zero time limit
(spent_limit_seconds = 0, or time_limit_seconds=0 where solve() takes
one); step_count_limit = 0 means no limit, not zero steps.
Extending a use case¶
docs/extending.md is the step-by-step guide: adding a move
(a MoveOperator registered in the use case's solver.cpp), a ruin operator,
changing the construction, and adding a hard or soft cost (a component under
constraints/, the assembly, the fast default path, the Python spec, tests and
docs). Each use case has extending.md next to its guide: one new constraint taken
through that use case's own files in six steps, from a pick in Python to the
default fast path, with the steps per second measured on the way.
How the extensions are built¶
setup.py builds one extension per use case
(optimaru.<use case>._core, for every subpackage with a _core.pyi) from
optimaru/<use case>/cpp/bindings.cpp and every .cpp under cpp/<ns>/
(not cpp/main.cpp, the demo), the same sources as the core library in its CMakeLists.txt. uv sync installs the package in editable mode and
builds the extensions in place, next to the Python files. OPTIMARU_USE_CASES
(comma-separated) limits the build to some use cases. uv rebuilds when a
.cpp / .hpp under optimaru/, setup.py, pyproject.toml or
OPTIMARU_USE_CASES changes; uv sync --reinstall-package optimaru forces it.