optimaru.vehicle_routing (Python)¶
Python bindings for the C++ vehicle-routing example in
optimaru/vehicle_routing/cpp — one solver, one module.
The problem: vehicles with capacities start from their depots;
customer visits have demands, time windows and service durations. Decide
which vehicle serves which visits, in what order, driving as little as
possible. Routes are open by default — a vehicle ends its day at its last
visit; give a vehicle an end_depot (its start depot or another) to charge
and time the leg there. A visit may have several time windows, a vehicle extra
capacity dimensions (weight, volume) and driver breaks. RouteSolution.vehicle_metrics
reports per-vehicle stops, load, driving seconds and meters, waiting, service and break
seconds and the route end time; these are post-processed from the finished routes
(vehicle_metrics()) and never scored. RouteSolution.breaks lists the breaks each
route takes and when.
Install and test¶
OPTIMARU_USE_CASES=vehicle_routing uv sync # builds only this use case's C++ extension
uv run pytest -q tests/vehicle_routing
Usage¶
from optimaru import vehicle_routing as vrp
locations = [vrp.Location(37.5665, 126.9780), # index 0: the depot
vrp.Location(37.5700, 126.9820)] # index 1: a customer
vehicles = [vrp.Vehicle("V1", capacity=10, start_location_index=0,
departure_time=7 * 3600)]
visits = [vrp.Visit("C1", "Customer 1", location_index=1, demand=3,
min_start_time=8 * 3600, max_end_time=18 * 3600,
service_duration=600)]
plan = vrp.VehicleRoutePlan("demo", locations, vehicles, visits)
vrp.solve(plan, time_limit_seconds=2.0, random_seed=42) # in place; returns the plan
print(plan.score) # 0hard/0medium/-38soft
print(plan.routes()) # {'V1': ['C1']}
vrp.solve also takes parallel_solver_count, stop_at_first_feasible,
full_assert (re-verifies every incremental score against a full recompute; a
debugging aid, much slower), on_new_best, constraints and a full config: a
vrp.SolverConfig, whose fields the keywords override on a copy.
vrp.Solver(config).solve(plan) runs the same solver locally. Set options on
config before constructing the solver.
config.acceptance.rule chooses the rule local search accepts a move by (late
acceptance by default); its parameters are listed under
Choosing the acceptance rule.
- Times are integer seconds from a common day start (
8 * 3600= 08:00). - Vehicles of one depot should share its location index (
start_location_index): the operators that skip equivalent idle vehicles compare indices. VehicleRoutePlantakes one driving-seconds and one driving-meters matrix per travel profile (durations=,distances=, lists of square matrices over the locations;Vehicle.profile_indexpicks one). A matrix not given is precomputed from the coordinates when the plan is constructed: haversine meters, and those meters at 50 km/h for the seconds.Vehicle.end_location_indexis where the route ends, -1 (the default) for an open route.- Score (hard, medium, soft; lexicographic), at the default weights: hard =
capacity excess (
vehicle_capacity_cost) + time-window lateness (max_end_time_cost) (0 = feasible), medium = −(penalty minutes of unassigned visits,unassigned_visits_cost; folded into the engine's soft asmedium * 10^9), soft = −(total driving seconds,travel_time_cost). - Visits that share
Visit.group_indexare one job: they ride one vehicle together or all stay unassigned, andVisit.after_visit_indicesputs a partial order on them (visit_group_cost,visit_order_cost, both hard;VisitModel.groupandVisitModel.afterin the JSON layer). See Visit groups. Visit(..., time_windows=[(start, end), ...])gives a visit several windows instead ofmin_start_time/max_end_time(max_end_time_costmeasures lateness against the last);Vehicle(..., capacities=[...])andVisit(..., demands=[...])add capacity dimensions (vehicle_capacities_cost, hard);Vehicle(..., breaks=[vrp.Break(earliest_start, latest_start, duration)])lists the driver's breaks (vehicle_break_cost, hard, for one that starts late), and after a solve orcalculate_scoreVehicle.break_start_timesandVehicle.break_positionssay where the route takes them. The same fields onVisitModel/VehicleModelin the JSON layer. See Time windows, Driver breaks and Capacity dimensions.VehicleRoutePlan(..., profile_visits=[vrp.ProfileVisits(forbidden, preferred)])lists, per kind of vehicle, the visits it may not serve and those it is preferred for;Vehicle.profile_visits_indexpicks one (-1 for none). Scored byprofile_forbidden_visit_cost(hard, always on) andprofile_preferred_visit_cost(soft);TravelProfile.forbidden_visitsandpreferred_visitsin the JSON layer. See Profile visits.vrp.constraint_info()lists every constraint with its default level and weight (the C++ components'kDefaultLevel/kDefaultWeight);optimaru.vehicle_routing.constraintspicks, re-weights and flips them forSolver.solve_with_constraints/solve_request(..., constraints=...). Every constraint takes five knobs (weight,level,exponentand the keyword-onlyoffset/clip) and may be picked several times, each pick with its own knobs ([TravelTimeCost(), TravelTimeCost(exponent=2, offset=3600)]is the driving time plus the square of every second beyond one hour per vehicle). The constraint table and the knobs are in the use-case README.
The default VRP configuration also enables a granular descent (Toth & Vigo 2003):
nearby route pairs are searched with best-improvement relocate, swap, 2-opt,
2-opt* and bounded CROSS-exchange moves. Set strategies.granular_descent = False (or
lower strategies.descent_weight) when a cheaper sampled neighbourhood is preferred.
JSON in, JSON out (pydantic)¶
With an API key set (optimaru.use_api, OPTIMARU_API_KEY), solve_request runs on the
optimaru API and solve(plan) is refused: a compiled plan is solved in place, which the API
cannot do. See Solving on the optimaru API.
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="D1", location=(37.5665, 126.9780))],
vehicles=[VehicleModel(id="V1", capacity=10, start_depot="D1")],
visits=[VisitModel(id="C1", location=(37.57, 126.982), demand=3,
min_start_time=8 * 3600, max_end_time=18 * 3600,
service_duration=600)],
),
)
solution = solve_request(request) # -> RouteSolution
print(solution.routes, solution.score, solution.total_driving_seconds)
Depots and travel profiles¶
A route starts at its vehicle's start_depot and ends at its end_depot; without
one (the default) the route is open and ends at its last visit. Depots and visits
share one id space: no depot may have a visit's id. An idle vehicle drives nothing,
even when its two depots differ.
Driving comes from the vehicle's travel profile (VehicleModel.profile, "default"
unless set). RoutingInput.profiles names each profile's pairwise driving seconds
(durations) and meters (distances), keyed by depot and visit ids,
{from_id: {to_id: value}}:
from optimaru.vehicle_routing.models import TravelProfile
profiles = {
"car": TravelProfile(durations={"D1": {"C1": 300}, "C1": {"D1": 320}},
distances={"D1": {"C1": 2_100}, "C1": {"D1": 2_300}}),
"bike": TravelProfile(durations={"D1": {"C1": 700}, "C1": {"D1": 720}}),
}
# RoutingInput(..., profiles=profiles), and VehicleModel(..., profile="bike")
- A pair the dicts leave out costs the profile's
missing_value, 10,000,000 by default (MISSING_TRAVEL_VALUE: about 116 days or 10,000 km), so a route avoids that leg wherever it can; a place to itself costs 0 unless given. - A profile without
durationsor withoutdistances, and every vehicle whenprofilesis empty, drives straight lines between the coordinates: haversine meters, and those meters at 50 km/h for the seconds. An empty dict is refused: it would make every pair missing. - A vehicle naming a profile that
profilesdoes not hold is refused, as is a dict keyed by an id that is no depot or visit. same_travel_as="car"drives a profile on the travel of the profilecar, which gives its own: profiles that differ only in their visit lists (forbidden_visits,preferred_visits, see Profile visits) share one set of dicts and one matrix in the engine.solve_requestturns each distinct travel into one square matrix over the depots, then the visits, before the solve. For 1,000 places with both dicts given (40 MB of JSON), parsing and validating the request took 0.11 s and building the matrices 0.06 s on an M4 Max.travel_time_costprices the seconds;travel_distance_cost(opt-in, weight 0) prices the meters. Its move previews walk the candidate route, wheretravel_time_costanswers from prefix sums, so it slows the search on long routes.RouteSolution.total_driving_metersand each vehicle'sdriving_metersreport the meters either way.
Everything round-trips through JSON (model_validate_json /
model_dump_json); fields are snake_case, classes PascalCase.
Several windows, breaks and capacity dimensions¶
from optimaru.vehicle_routing.models import BreakModel
VehicleModel(id="V1", capacity=40, capacities=[1200, 18], start_depot="D1", end_depot="D1",
breaks=[BreakModel(earliest_start=11 * 3600, latest_start=13 * 3600, duration=1800)])
VisitModel(id="C1", location=(37.57, 126.982), demand=2, demands=[350, 4], service_duration=600,
time_windows=[(9 * 3600, 12 * 3600), (14 * 3600, 18 * 3600)])
A solution then carries breaks, per vehicle that takes one: BreakStop(break_index,
start_time, duration, position), position being how many of the route's visits come
before the break; vehicle_metrics[...].break_seconds adds up their durations, and
end_time includes them. VisitStop.arrival_time is the arrival at the visit, the breaks
before it included; service starts at models.service_start(visit, arrival_time), when its
window opens. Where a route takes each break, and what a visit with several windows waits
for, is in the guide.
Parameters and their costs¶
A request that sets a field which acts only through a cost, while its constraints leave
every such cost out, is refused with ValueError naming the field and the costs to add;
a pick at weight 0 counts. models.parameter_uses(model) lists the fields an input sets,
and Parameters and their costs has the table.
It is checked where the input is the JSON model (solve_request, solve(model)); a
compiled problem is solved as given.
Files¶
optimaru/vehicle_routing/
├── __init__.py re-exports the core
├── constraints.py the constraint specs (one class per C++ component), built on optimaru/_constraint.py
├── models.py pydantic request/response layer
├── _core.pyi stubs of the compiled module
└── cpp/ bindings.cpp (the _core module, a thin wrapper), vrp/ (the C++ core), main.cpp (the demo)
tests/vehicle_routing/ correctness + model tests (pytest); cpp/ holds the C++ tests