Vehicle Routing — C++¶
The C++ lives in optimaru/vehicle_routing/cpp/; the paths below are relative to it,
and its C++ tests are in tests/vehicle_routing/cpp/.
The C++17 optimization core of the vehicle-routing use case, derived from the
Timefold Quickstarts vehicle-routing example (Apache-2.0; see the repository NOTICE): the
domain model, the scoring (hard / medium / soft levels) and the
solve, running on the generic engine in core/optimaru/.
Scope: optimization core only — no REST layer, no web UI.
Build & run¶
cmake -B build -DOPTIMARU_USE_CASES=vehicle_routing && cmake --build build -j
./build/vehicle_routing/vrp_demo # default: 25 visits, 6 vehicles, 3s
./build/vehicle_routing/vrp_demo 77 6 5 # 77 visits, 6 vehicles, 5s
./build/vehicle_routing/vrp_demo 77 6 5 --no-alns # ruin & recreate off, as a control
./build/vehicle_routing/vrp_test # hand-computed fixtures + engine integration
The C++ types¶
| Type | What it holds / does |
|---|---|
struct VehicleRoutePlan (domain.hpp) |
the whole problem and its solution: locations, vehicles, visits, the unassigned pool unassignedVisitIndices, one durationMatrices and one distanceMatrices entry per travel profile, and the score |
struct Vehicle |
capacity, start location, end location (-1 = open route), travel profile, departure time, the optional route policies, and the decision: std::vector<int> visitIndices, the ordered visits it serves |
struct Visit |
location, demand, time window, service duration, unassigned penalty, group and the visits it comes after (+ derived vehicleIndex, arrivalTime) |
ScoreCalculator::updateShadowVariables |
recomputes every visit's derived vehicleIndex / arrivalTime from the routes |
Score |
the hard / medium / soft levels (lexicographic compare): the engine's optimaru::HardMediumSoftScore |
HaversineDrivingTimeCalculator (haversine.{hpp,cpp}) |
the straight-line fallback: haversine meters, and those meters at 50 km/h for the seconds; fillMissingMatrices fills every profile matrix left empty |
ScoreCalculator (reference) + VehicleRoutingIncrementalScoreCalculator (live) |
the four default constraints: a full recompute, and the incremental calculator the search calls |
Solver (solver.hpp) |
wraps core/optimaru/'s optimaru::Solver: construction heuristic + local search |
Solver::Config::time_limit |
wall-clock budget (default 30 s) |
Solver::Config::target_score |
stop early once the best score reaches it; {0, kNoLevelFloor, kNoLevelFloor} stops at the first feasible solution, which may still leave visits unassigned |
The four constraints¶
The four default constraints, under their
component names (vrp/constraints/<subject>_cost.hpp; the
registry name is the struct name with a lower-case first letter):
- Hard
VehicleCapacityCost(vehicleCapacityCost) — penalizetotalDemand - capacitywhen overloaded. - Hard
MaxEndTimeCost(maxEndTimeCost) — penalize lateness (arrivalTime + serviceDurationpastmaxEndTime), rounded up to whole minutes. - Medium
UnassignedVisitsCost(unassignedVisitsCost) — penalize each unassigned visit byVisit::unassignedPenalty(), which defaults to its service duration in minutes but can be set per visit — see below. Weight 1 in medium units; the domain folds medium into the engine's soft level asmedium * 10^9(kMediumFoldindomain.hpp). - Soft
TravelTimeCost(travelTimeCost) — penalize each vehicle's total driving seconds (start depot → visits, plus the leg toVehicle::endLocationIndexwhen it is set; routes are open by default and end at their last visit), on the matrix of the vehicle's profile.
The plugin path adds the optional route policies (MaxTravelTimeCost,
MaxRouteDurationCost, VehicleMaxEndTimeCost, MaxStopsCost,
MaxRouteRadiusCost, MinCapacityUtilizationCost, VehicleFixedCost) and
the opt-in weight-0 objectives (EnclosingCircleRadiusCost,
RouteDurationCost, LatencyCost), and the two constraints of visit groups
(VisitGroupCost, VisitOrderCost: Visit::groupIndex and
Visit::afterVisitIndices), and the two constraints of profile visits
(ProfileForbiddenVisitCost, always on, and ProfilePreferredVisitCost:
VehicleRoutePlan::profileVisits and Vehicle::profileVisitsIndex); see the
package README for the table and for how groups are placed and moved
(visit_insertion.hpp, group_moves.hpp). A C++ caller that assembles its own
constraints for Solver::solve(plan, calculator) passes the assembly through
withAlwaysOnConstraints(assembly, plan) (vrp/constraints.hpp) first, as the
Python bindings do: it adds ProfileForbiddenVisitCost when the plan forbids
visits and refuses a plan with preferred visits whose assembly lacks
ProfilePreferredVisitCost; the solve itself scores exactly what it is given.
How it runs on the generic engine¶
Solver (solver.hpp) is a thin wrapper that translates its
Solver::Config into an optimaru::Settings. The engine then does:
- Construction heuristic — cheapest insertion, in First-Fit-Decreasing order (tightest time window and largest demand first).
- Local search — the sampled move mix (relocate / swap / 2-opt / or-opt /
2-opt* tail swap / CROSS-exchange), plus a granular
best-improvement descent (Toth & Vigo 2003) on nearby route pairs. The descent enumerates
relocate, swap, 2-opt, 2-opt* and bounded ExchangeNM moves, then applies
the best candidate through the same acceptor (late acceptance by default).
It is enabled by
granular_descentand controlled bygranular_descent_max_segment,granular_descent_candidate_routes, anddescent_weight. An ejection chain (ejection_chain_weight) covers what single moves cannot reach on a tightly loaded fleet: it inserts an unassigned visit (or takes the best-soft relocation that breaks capacity), repairs the breach with strictly hard-improving relocations and swaps, and lets the acceptor judge the whole chain as one move. An iterated local search (iterated_local_search_weight) is the main engine on large instances: ruin a few visits (iterated_local_search_min_ruin..MaxRuin), repair them, then descend with relocate / swap / 2-opt / 2-opt* / CROSS (and Or-opt up toiterated_local_search_max_segment) around every touched visit's nearby neighbours until the routes are locally optimal, and let the acceptor judge the local optimum. All of these strategies score candidates through the calculator's move previews (incremental_calculator.hpp): O(1) from per-route prefix sums on a plan where no visit waits for its window, and one walk of the candidate route on a plan with waiting (time windows that open after departure). On the plugin path the engine's decomposed calculator previews a move per component: the four default components answer in O(pieces) from shared per-route prefix sums (constraints/route_sums.hpp), the optional policies by re-costing the written-out candidate route, so the same strategies run on any constraint assembly. - Adaptive ruin & recreate (ALNS) — destroy-and-repair runs as an
acceptor-judged move (
ruin_recreate_as_move_weight). The unconditional stagnation kick is available (ruin_recreate = true) but off by default: on a tightly loaded fleet the kicked solution is one the search never recovers from, and the best stops moving (seeSolver::Config).
The solver uses adaptive large-neighborhood search with
four operator-selection schemes (roulette wheel, segmented roulette wheel,
α-UCB, random), configurable acceptance criteria, and the ruin operators that
matter on routing problems — SISR substring removal and whole-route removal
alongside random / related / worst. Everything is on Solver::Config;
ruin_recreate = true turns the stagnation kick on (off by default, see above).
Two design points worth knowing¶
The unassigned pool. A visit may be left unassigned,
but the engine's sequence-shape requires every element to live in exactly one list.
So VehicleRoutePlan carries one extra virtual list at index
vehicles.size() holding the unassigned visits. That is what makes assigning
and unassigning ordinary relocate moves — with genuinely list-less elements the
solver could never drop an unprofitable visit nor recover a dropped one, and
the medium-level constraint would be unreachable.
Visit::unassignedPenaltyMinutes. The default rule — penalize an unassigned
visit by its service duration — is degenerate when service durations are 0 or a
few seconds: the penalty rounds to zero and "route nothing" becomes the
optimum. This field states what dropping a visit actually costs, defaulting to
kUnassignedPenaltyAuto, which applies the default rule. Real
instances (see the benchmark) set it explicitly.
Scoring: two implementations, checked against each other¶
ScoreCalculator::score— the full recompute, and the readable statement of the constraints. Authoritative:Solver::solvefinishes with it.calculateScore(plan)(vrp/solver.hpp) is this call for a plan without visit groups and the default constraint assembly for a plan with them, which is howSolver::solve(plan)scores each.VehicleRoutingIncrementalScoreCalculator— what the engine actually calls during search, maintaining per-route aggregates so a move costs O(route length) instead of O(instance).
They must agree. vrp_test checks this directly over 400 random list moves,
and ScoreChecks::Full re-verifies the incremental score against a
full recompute after every move (including the ruin & recreate path).