optimaru.vehicle_routing¶
Generated from the sources of optimaru/vehicle_routing/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.vehicle_routing ¶
Vehicle routing — C++ core with Python helpers.
Location, Visit, Vehicle, VehicleRoutePlan, Score, Solver,
SolverConfig, AcceptorType, OperatorSelectionType and calculate_score
come from the compiled C++ core (_core). Each vehicle's ordered
visit_indices list (its route) is the decision; a visit
missing from every route is unassigned (penalized on the medium score level)
and ends up in plan.unassigned_visit_indices after solving. solve(plan, ...)
solves a plan in place and returns it; solve_request does the same for a
models request.
The solver is the shared engine in core/optimaru/: a cheapest-insertion construction
heuristic, then local search over relocate / swap / 2-opt / or-opt / tail-swap
moves, interleaved with adaptive ruin & recreate (ALNS) — random, related,
worst, SISR substring and whole-route ruins under an adaptive operator
selection scheme, repaired by regret-k insertion. Every ALNS knob is on
SolverConfig. Destroy-and-repair runs as an acceptor-judged move by default;
the unconditional stagnation kick is off (ruin_recreate = True turns it on —
on a tightly loaded fleet it stalls the search, see Solver::Config). Two more
strategies run by default on top of the move mix: an ejection chain
(ejection_chain_weight) for the slack shifts a tightly loaded fleet needs,
and an iterated local search (iterated_local_search_weight: ruin a few
visits, repair, descend to a local optimum) that does most of the work on
large instances; with it the nearby neighbourhood is 25 visits
(driving_time_nearby_size). See Solver::Config for the measurements behind
each default.
Score convention (hard / medium / soft), at the default weights:
- hard — capacity excess (
vehicle_capacity_cost) + time-window lateness (max_end_time_cost), plus the optional route policies (max_travel_time_cost,max_route_duration_cost,vehicle_max_end_time_cost,max_stops_cost,max_route_radius_cost). 0 = feasible. - medium — -(penalty minutes of unassigned visits)
(
unassigned_visits_cost); the engine folds it into soft asmedium * 10^9. - soft — -(total driving seconds) (
travel_time_cost), plusmin_capacity_utilization_cost,vehicle_fixed_costand the opt-in weight-0 objectives.
Visits that share a group (Visit.group_index, VisitModel.group) are one job:
they ride one vehicle together or all stay unassigned (visit_group_cost, hard),
and after (Visit.after_visit_indices) puts a partial order on them
(visit_order_cost, hard). A group operator moves a group between vehicles as one
unit (group_ruin_recreate).
A vehicle's profile may list visits it may not serve (ProfileVisits,
TravelProfile.forbidden_visits; profile_forbidden_visit_cost, hard and always on)
and visits it is preferred for (TravelProfile.preferred_visits;
profile_preferred_visit_cost, soft).
Compared lexicographically: hard dominates medium dominates soft.
constraint_info() lists every constraint with its default level and weight;
optimaru.vehicle_routing.constraints picks and re-weights them.
optimaru.vehicle_routing.models ¶
Pydantic request/response models for the vehicle-routing solver.
JSON-friendly in/out (snake_case fields, PascalCase classes):
from optimaru.vehicle_routing.models import (DepotModel, RoutePlanRequest, RoutingInput,
VehicleModel, VisitModel, solve_request)
request = RoutePlanRequest(
time_limit_seconds=2,
model_input=RoutingInput(
depots=[DepotModel(id="D", location=(37.5, 127.0))],
vehicles=[VehicleModel(id="V1", capacity=10, start_depot="D")],
visits=[VisitModel(id="A", demand=3, location=(37.51, 127.01),
min_start_time=8 * 3600, max_end_time=18 * 3600,
service_duration=600)],
),
)
solution = solve_request(request)
print(solution.routes) # {"V1": ["A"]}
print(solution.score) # "0hard/0medium/-...soft"
Times are integer seconds from a common day start; locations are
(latitude, longitude) pairs. A route starts at its vehicle's start_depot and
ends at its end_depot, or at its last visit when there is none (an open route).
Driving seconds and meters come from the vehicle's travel profile
(RoutingInput.profiles, dicts keyed by depot and visit ids); without one,
straight lines between the coordinates. A profile also names the visits its
vehicles may not serve (forbidden_visits) and those they are preferred for
(preferred_visits).
DepotModel ¶
Bases: StrictModel
A place where routes start or end.
TravelProfile ¶
Bases: TravelProfile
How a kind of vehicle drives (see optimaru._routing.TravelProfile), and which visits it takes.
RoutingInput ¶
Bases: StrictModel
RoutePlanRequest ¶
Bases: SolveRequest
The routing problem with the settings of one solve (see SolveRequest for those).
VehicleMetrics ¶
Bases: StrictModel
Per-vehicle figures derived from a finished route (post-processing).
Nothing here is scored. The numbers are recomputed from the reported stop order and arrival times with the vehicle's travel profile.
to_plan ¶
to_plan(model_input: RoutingInput) -> _core.VehicleRoutePlan
Build the C++ VehicleRoutePlan from the pydantic input.
The locations are the depots, then the visits, in input order; each profile's
dicts become square matrices over them (profile_matrices), and the engine
fills what a profile does not give from the coordinates. The visit lists of
the profiles the vehicles drive on become ProfileVisits entries, which each
vehicle names by profile_visits_index.
vehicle_metrics ¶
vehicle_metrics(plan: VehicleRoutePlan, routes: dict[str, list[VisitStop]]) -> dict[str, VehicleMetrics]
Post-process finished routes into per-vehicle figures.
Works for any backend: it only needs the stop order and the arrival times
the backend reported, and re-derives departures as
max(arrival, min_start_time) + service_duration.
parameter_uses ¶
parameter_uses(model_input: RoutingInput) -> list[ParameterUse]
The parameters model_input sets away from their defaults that act only through a cost.
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"). Forbidden visits are not here (their cost is always on), nor demand and profile
distances (the solution reports the load and the driving meters from them, whatever the
constraints).
solve_request ¶
solve_request(request: RoutePlanRequest, *, constraints=None) -> RouteSolution
Solve a routing request end-to-end and return the pydantic solution.
A parameter set away from its default whose costs the constraints leave out is refused
with ValueError (parameter_uses): the solve would not score it.
with_initial_solution ¶
with_initial_solution(problem: RoutePlanRequest, solution: RouteSolution | dict[str, Any]) -> RoutePlanRequest
Return a copy of problem whose search starts from solution.
solution is what solve_request returned, as the model or as its JSON
dict. Each vehicle's initial_route becomes the visit ids of its route
there, replacing what problem had; a vehicle the solution leaves out
starts empty. Vehicles and visits are matched by id.
Visits in no route, unassigned ones included, are placed by construction.
A solution that routes every visit is the exact starting point. Raises
ValueError on an unknown vehicle or visit, or a visit routed twice.
optimaru.vehicle_routing.constraints ¶
Constraint assembly specs — an API for picking the cost function declaratively.
The default path (Solver(cfg).solve(plan)) enables the four core constraints;
the per-vehicle route-policy constraints cost 0 while their parameter is 0. The
travel distance, enclosing-circle radius, route duration and latency are opt-in
objectives with default weight 0.
This module is the alternative path next to it: pick constraints, change weights, change
levels, shape the cost, and pass the list to solve_with_constraints.
A constraint list reads one way: one class call per constraint::
import optimaru.vehicle_routing as vrp
from optimaru.vehicle_routing.constraints import (
TravelTimeCost, UnassignedVisitsCost, VehicleCapacityCost, get_constraints,
)
solver = vrp.Solver(cfg)
solver.solve_with_constraints(plan, get_constraints()) # the defaults as-is
solver.solve_with_constraints(plan, [ # picked
VehicleCapacityCost(), UnassignedVisitsCost(), TravelTimeCost(weight=10),
])
Only listed constraints are scored — leave one out and its term disappears from the
score. (The module also carries ready-made default instances: vehicle_capacity_cost
is VehicleCapacityCost(), and so on.)
Every spec takes five knobs:
weightlinear multiplier on the constraint cost, in units of its level.None= the C++ component default (vrp.constraint_info()lists them).levelNone= the default level, otherwise aLevelor its name (Level.MEDIUMor"medium"). Any flippable constraint may take any of the three levels.UnassignedVisitsCostis the one medium constraint (folded into the engine's soft level asmedium * 10^9):level="hard"charges one hard unit per penalty minute,level="soft"one soft unit per penalty minute, and aweightis in units of the level in effect.exponentsign-preserving power shaping:weight * sign(c) * |c| ** exponent, per vehicle for the route constraints and on the total for the globalUnassignedVisitsCost. 2.0 = squared, so concentrated violations grow much costlier.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;Falseshapesc - offsetas it is, so a vehicle below the offset — an idle one (cost 0) included — lowers the penalty. The unassigned pool is no vehicle: a route constraint never charges it. With an offset it is refused on hard (VehicleCapacityCostby 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. Travel time plus the cube of every second beyond two hours of driving per vehicle::
solver.solve_with_constraints(plan, [
VehicleCapacityCost(),
UnassignedVisitsCost(),
TravelTimeCost(),
TravelTimeCost(weight=1e-9, exponent=3, offset=7200),
])
vrp.constraint_costs(plan, picks) keys the second pick "travel_time_cost#2".
Names (name) are the C++ component names in snake_case
(VehicleCapacityCost -> vehicle_capacity_cost). The core derives them
mechanically, so there is no hand-maintained alias table — check them with
vrp.list_constraints(). Module-level instance names use the same snake_case,
so they match the strings list_constraints() prints.
parallel_solver_count applies on the plugin path: every start scores on its own copy
of the picks (in C++, only the Solver::solve overload that takes one caller-owned
calculator stays a single start). The driving-time-guided selection does not apply there.
Details are in the comments of cpp/vrp/solver.hpp.
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.
VehicleCapacityCost
dataclass
¶
MaxEndTimeCost
dataclass
¶
Bases: Constraint
Minutes (rounded up) by which a visit's service ends after its time window. Default: hard, weight 1.
Measured from arrival + service duration, not service start. The vehicle's own end time is VehicleMaxEndTimeCost.
TravelTimeCost
dataclass
¶
Bases: Constraint
Driving seconds per vehicle, start depot -> visits (-> end depot). Default: soft, weight 1.
An idle vehicle drives nothing, so it costs nothing.
TravelDistanceCost
dataclass
¶
Bases: Constraint
Driving meters per vehicle, start depot -> visits (-> end depot). Default: soft, weight 0 (opt-in).
Read from the distance matrix of the vehicle's travel profile; an idle vehicle drives nothing.
Its move previews walk the candidate route (travel_time_cost answers from prefix sums),
so weighing it in slows the search on long routes.
MaxTravelTimeCost
dataclass
¶
MaxRouteDurationCost
dataclass
¶
Bases: Constraint
Seconds of working time, waits and service included, above the limit. Default: hard, weight 1.
VehicleMaxEndTimeCost
dataclass
¶
Bases: Constraint
Seconds by which the route end passes Vehicle.max_end_time. Default: hard, weight 1.
A visit's own time window is MaxEndTimeCost.
MaxStopsCost
dataclass
¶
MaxRouteRadiusCost
dataclass
¶
Bases: Constraint
Meters of route radius from the vehicle's start depot above the limit. Default: hard, weight 1.
EnclosingCircleRadiusCost
dataclass
¶
Bases: Constraint
Radius (meters) of the minimum circle enclosing a route's visits. Default: soft, weight 0 (opt-in).
Unlike max_route_radius_cost, which measures from the start depot, no depot is
not one of the circle's points. Give it a weight to prefer compact routes.
MinCapacityUtilizationCost
dataclass
¶
Bases: Constraint
Shortfall of used vehicles below the target minimum load. Default: soft, weight 1.
RouteDurationCost
dataclass
¶
LatencyCost
dataclass
¶
VehicleFixedCost
dataclass
¶
VisitOrderCost
dataclass
¶
Bases: Constraint
Visits served before one they have to come after. Default: hard, weight 1000.
after on a visit names visits of its group that are served earlier on the route:
a partial order on the group. Engine-only (no CP-SAT plugin).
VisitGroupCost
dataclass
¶
Bases: Constraint
Grouped visits that are apart from the rest of their group. Default: hard, weight 1000.
The visits of a group are one job: they ride one vehicle together, or all wait.
A global constraint, since a group spans routes. Engine-only (no CP-SAT plugin).
ProfileForbiddenVisitCost
dataclass
¶
Bases: Constraint
Visits served by a vehicle whose profile forbids them. Default: hard, weight 1000; always on.
TravelProfile.forbidden_visits names the visits a vehicle on the profile may not
serve. Every solve scores this constraint hard, listed or not: on a plan with forbidden
visits, a selection without a hard instance of it at a weight above 0 gets one at its
defaults, beside any softer or weight-0 pick, which scores as picked but does not
switch the rule off (on a plan without forbidden visits nothing is added). Leaving
a visit unassigned costs only medium, so one that no vehicle may serve waits.
Engine-only (no CP-SAT plugin).
ProfilePreferredVisitCost
dataclass
¶
Bases: Constraint
Preferred visits served by a vehicle whose profile does not prefer them. Default: soft, weight 600.
TravelProfile.preferred_visits names the visits that should go to a vehicle on the
profile. A visit some vehicle's profile prefers costs one unit when a vehicle whose
profile does not prefer it serves it; an unassigned visit is left to
unassigned_visits_cost. At weight 600 against travel_time_cost's 1 per driving
second, a vehicle that does not prefer a visit takes it only when that saves more than
ten minutes of driving. A request whose vehicles drive on a profile with preferred visits
needs this constraint among its constraints (ValueError otherwise); a profile no vehicle
drives on prefers nothing. Engine-only (no CP-SAT plugin).
UnassignedVisitsCost
dataclass
¶
Bases: Constraint
Penalty minutes of visits left off every route. Default: medium, weight 1.
The per-visit penalty defaults to the service time in whole minutes
(Visit.unassigned_penalty); it is penalty minutes, not a count. Unassigned
visits belong to no unit, so this is a global constraint. The weight is in
medium units; the domain folds the medium level into the engine soft level
as medium * 10^9.
get_constraints ¶
get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]
Return the cost function. Without arguments, every registered constraint.
When constraints is given, that list is used as-is — only the listed
constraints are scored::
get_constraints([VehicleCapacityCost(), UnassignedVisitsCost(), TravelTimeCost(weight=10)])
Same contract as the C++ applyConstraints: an empty list is an error (pass None for the defaults); 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 vrp.constraint_costs(plan) 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 = vrp.constraint_costs(plan)
score(raw) # default set
score(raw, [VehicleCapacityCost(), UnassignedVisitsCost(), TravelTimeCost(weight=10)])
score(raw, [TravelTimeCost(), TravelTimeCost(exponent=2, offset=3600)])
No solver and no search are involved. The arithmetic matches the engine —
each evaluated unit (a vehicle; the global's total) 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 — and profile_forbidden_visit_cost at its
defaults besides when costs holds one more instance of it than the picks
(with_always_on): every solve scores it hard on a plan with forbidden visits,
and vrp.constraint_costs reports that instance. Unknown names raise ValueError.
The returned value is the engine-level (hard, soft): the medium level
(unassigned_visits_cost) is folded into soft as medium * 10^9, the
medium_fold every entry of costs carries. To compare with the split
levels of plan.score, fold the same way first.
optimaru.vehicle_routing._core ¶
Type stubs for optimaru.vehicle_routing._core — the vehicle-routing C++ solver.
Times are integer seconds from a common day start. Each vehicle's ordered
visit_indices (its route) is the decision; a visit in no route is
unassigned.
Score (hard / medium / soft, lexicographic), at the default weights: hard = capacity excess + time-window lateness (0 = feasible), medium = -(penalty minutes of unassigned visits), folded into the engine's soft as medium * 10^9; soft = -(total driving seconds). The weights are the C++ components' defaults (constraint_info()).
AcceptorType ¶
Bases: Enum
Local-search acceptance criterion.
OperatorSelectionType ¶
Bases: Enum
Adaptive ruin-operator selection scheme.
Location ¶
Visit ¶
One customer stop (demand, time window, service).
group_index
instance-attribute
¶
group_index: int
The group this visit travels in; -1 == none. The visits that share a group ride one vehicle together, or all wait (visit_group_cost).
after_visit_indices
instance-attribute
¶
after_visit_indices: list[int]
Indices into VehicleRoutePlan.visits of the visits of its group this one is served after on the route (visit_order_cost). Read the whole list and assign a whole list: appending to the value read changes a copy.
vehicle_index
property
¶
vehicle_index: int
Derived: index of the serving vehicle; -1 == unassigned.
ProfileVisits ¶
What one kind of vehicle may serve: the visits it may not
(profile_forbidden_visit_cost) and those it is preferred for
(profile_preferred_visit_cost). A vehicle names its entry with
Vehicle.profile_visits_index. Both lists hold indices into
VehicleRoutePlan.visits in strictly increasing order, none in both.
Vehicle ¶
start_location_index
instance-attribute
¶
start_location_index: int
Where the route starts. Vehicles of one depot should share its location index: the operators that skip equivalent idle vehicles compare indices.
end_location_index
instance-attribute
¶
end_location_index: int
Where the route ends; -1 (the default) leaves the route open at its last stop: no closing leg is driven or timed.
profile_index
instance-attribute
¶
profile_index: int
Which of the plan's matrices the vehicle drives on.
profile_visits_index
instance-attribute
¶
profile_visits_index: int
Which entry of VehicleRoutePlan.profile_visits says what the vehicle may
serve; -1 (the default) for none.
visit_indices
instance-attribute
¶
visit_indices: list[int]
The decision: the ordered route (indices into visits).
VehicleRoutePlan ¶
The problem and its routes. Constructing it assigns location indices and
takes one driving-seconds and one driving-meters matrix per profile: as many
profiles as the longer list holds (one at least); a matrix not given (None,
or past the end of its list) is the haversine fallback. profile_visits lists
what each kind of vehicle may not serve or is preferred for (ValueError for an
index out of range, a list out of order, a visit in both lists).
unassigned_visit_indices
instance-attribute
¶
unassigned_visit_indices: list[int]
The unassigned pool: visits the solver chose not to route. Filled by solve(); penalized on the medium score level.
driving_time ¶
driving_time(from_location: int, to_location: int, profile: int = 0) -> int
Driving seconds between two location indices in a profile.
driving_distance ¶
driving_distance(from_location: int, to_location: int, profile: int = 0) -> int
Driving meters between two location indices in a profile.
unassigned_visit_ids ¶
unassigned_visit_ids() -> list[str]
Ids of the visits left unassigned (convenience view).
rebuild_unassigned_pool ¶
rebuild_unassigned_pool() -> None
Recompute unassigned_visit_indices from the current routes.
SolverConfig ¶
best_score_limit
instance-attribute
¶
best_score_limit: tuple[int, int, int]
(hard, medium, soft): stop early once bestScore >= this. -(263) on medium or soft means no floor on the soft side (only hard is compared), so (0, -(263), -(2**63)) stops at the first feasible solution.
parallel_solver_count
instance-attribute
¶
parallel_solver_count: int
Independent parallel starts; the best final score wins.
full_assert
instance-attribute
¶
full_assert: bool
Re-verify every incremental score against a full recompute after every move (a debugging aid; much slower).
first_fit_decreasing
instance-attribute
¶
first_fit_decreasing: bool
Construction heuristic order: tightest time window and largest demand first (True), or plain input order (False).
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
LATE_ACCEPTANCE: 0 = auto: clamp(60000 // len(visits), 100, 400) — shorter for larger instances, keeping the acceptance horizon roughly constant in wall-time.
entity_tabu_size
instance-attribute
¶
entity_tabu_size: int
ENTITY_TABU: for how many steps a moved entity stays tabu (7 by default; >= 0).
simulated_annealing_starting_temperature
instance-attribute
¶
simulated_annealing_starting_temperature: tuple[int, float]
SIMULATED_ANNEALING's (hard, soft) starting temperature, cooling to 0 over the solve. (0, 0), the default, = auto: hard 0, soft = simulated_annealing_temperature_fraction x |start soft| (at least 1); the soft level alone, without the medium level of the unassigned visits.
simulated_annealing_temperature_fraction
instance-attribute
¶
simulated_annealing_temperature_fraction: float
The auto temperature's fraction of the start's soft level, without the medium level of the unassigned visits (0.01 by default; > 0).
great_deluge_water_level_step
instance-attribute
¶
great_deluge_water_level_step: tuple[int, float]
GREAT_DELUGE: how much the (hard, soft) water level, which starts at the start's score, rises per step. (0, 0), the default, leaves it there: only moves that keep the score at or above the start's are taken. A soft amount you give here, like an explicit starting temperature, is on the scale the search compares in, where one unit of the medium level (a penalty minute of an unassigned visit) counts 10^9: only the automatic temperature leaves the medium level out.
step_counting_hill_climbing_size
instance-attribute
¶
step_counting_hill_climbing_size: int
STEP_COUNTING_HILL_CLIMBING: the bar is reset to the current score every this many steps (400 by default; > 0).
record_to_record_start_gap
instance-attribute
¶
record_to_record_start_gap: float
RECORD_TO_RECORD_TRAVEL: the gap below the best score that is still accepted at the start of the solve, as a fraction of the start's |soft| (0.02 by default; >= 0). The medium level is included here, at 10^9 per unit: a start that leaves work unassigned widens the gap.
record_to_record_end_gap
instance-attribute
¶
record_to_record_end_gap: float
RECORD_TO_RECORD_TRAVEL: the same gap at the end of the solve (0.0 by default; >= 0); the gap shrinks from the start gap to this one.
group_ruin_recreate
instance-attribute
¶
group_ruin_recreate: bool
The group operator: takes a visit group out, alone or with a few more visits, and puts each unit back whole at its cheapest feasible place. Only registered for a plan with groups.
group_ruin_max_visits
instance-attribute
¶
group_ruin_max_visits: int
The most visits the group operator takes out beside its first group (0 or more).
ruin_recreate_rewards
instance-attribute
¶
ruin_recreate_rewards: list[float]
Four rewards, indexed NEW_BEST / BETTER / ACCEPTED / REJECTED.
sisr_ruin
instance-attribute
¶
sisr_ruin: bool
SISR substring removal (Christiaens & Vanden Berghe).
route_ruin
instance-attribute
¶
route_ruin: bool
Whole-route removal — the only ruin that can free up a vehicle.
regret_k
instance-attribute
¶
regret_k: int
Repair strategy: >= 2 uses regret-k insertion, 0/1 plain greedy.
blink_rate
instance-attribute
¶
blink_rate: float
SISR blinking: probability of skipping a candidate placement.
on_new_best
instance-attribute
¶
on_new_best: Callable[[int, Score], None] | None
Progress callback (steps, best score). The score has the same three levels as the final plan.score: with solve_with_constraints both come from the chosen constraints' hard / medium / soft totals, so a soft total of 10^9 or more stays on soft instead of spilling into medium.
Solver ¶
Construction heuristic + local search + adaptive ruin & recreate (ALNS). Solves IN PLACE: fills vehicle.visit_indices, the unassigned pool, the derived fields and plan.score.
solve ¶
solve(plan: VehicleRoutePlan) -> None
Solve on the four core constraints, which do not include the vehicle limits: for a plan that sets one, call solve_with_constraints. A plan with a group of two visits or more (Visit.group_index) or a profile visit list (profile_visits) is the exception: it is scored with the default constraints, visit_group_cost, visit_order_cost and the two profile visit costs among them, every parallel start on a set of its own.
solve_with_constraints ¶
solve_with_constraints(plan: VehicleRoutePlan, constraints: Iterable[Any] | None = ...) -> None
Score the same solve with a caller-chosen constraint set (see optimaru.vehicle_routing.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. With parallel_solver_count above 1 every start is scored by its own copy of the picks. profile_forbidden_visit_cost is always on: a plan with forbidden visits is scored on it hard whether the list holds it or not (a soft or weight-0 pick of it scores beside the default instance). A plan with preferred visits needs profile_preferred_visit_cost in the list: ValueError otherwise.
ConstraintInfo ¶
Bases: NamedTuple
One constraint-catalog row, read off the C++ default assembly.
calculate_score ¶
calculate_score(plan: VehicleRoutePlan) -> Score
Recompute the derived fields and the score (also stores plan.score).
The score is the one solve(plan) stores: the four core constraints, or the default constraints when the plan has a group of two or more visits or a profile visit list.
list_constraints ¶
list_constraints() -> list[str]
Constraint names scored by this domain (default assembly order, snake_case): the seventeen per-vehicle constraints (vehicle_capacity_cost ... vehicle_fixed_cost, visit_order_cost, profile_forbidden_visit_cost, profile_preferred_visit_cost), then the two globals (visit_group_cost, unassigned_visits_cost). The same names optimaru.vehicle_routing.constraints uses.
constraint_costs ¶
constraint_costs(plan: VehicleRoutePlan, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]
Per-constraint, per-unit raw costs — before weight/exponent/offset/level
rounding. A unit is a vehicle (plus the unassigned pool as the last cell, always 0);
a global constraint reports one cost. optimaru.vehicle_routing.constraints.score() takes these
and produces a score:
{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, "units": [...],
"medium_fold": {"kind": "into_soft", "unit": 1e9}}}. None = the default
constraints; a pick list (as for solve_with_constraints) scores exactly those
picks (and profile_forbidden_visit_cost on a plan with forbidden visits, which every
solve scores), each entry carrying its pick's knobs, the k-th pick of a name keyed
"
constraint_info ¶
constraint_info() -> list[ConstraintInfo]
The constraint catalog, in list_constraints() order: the default level and weight of each constraint (unassigned_visits_cost is medium at weight 1 in medium units; the route policies hard at 1; visit_group_cost and visit_order_cost hard at 1000; travel_time_cost, min_capacity_utilization_cost and vehicle_fixed_cost soft at 1). All flippable, none a reward; default_enabled is False for the opt-in weight-0 objectives (travel_distance_cost, enclosing_circle_radius_cost, route_duration_cost, latency_cost).