Skip to content

optimaru.pickup_delivery

Generated from the sources of optimaru/pickup_delivery/ and the stubs of its compiled extension. The guide explains the model and the constraints in prose.

optimaru.pickup_delivery

Pickup and delivery with time windows (PDPTW) — C++ core, Python bindings.

A transport request is a pickup and a dropoff that one vehicle must serve, pickup first, without ever exceeding its capacity in between. That coupling is the whole difference from optimaru.vehicle_routing: a plain visit can be moved anywhere, a PDP stop drags its partner along.

The solution is PdpRoutePlan: each vehicle's ordered node_indices (its route) is the decision, and a stop in no route is unassigned (it lands in plan.unassigned_node_indices).

Score (hard / medium / soft, lexicographic), at the default weights:

  • hard — capacity peak along the route (vehicle_capacity_cost), time-window lateness (max_end_time_cost), and the coupling constraints (paired_request_cost, same_vehicle_cost, pickup_before_dropoff_cost: a request is routed whole or not at all, on one vehicle, pickup before dropoff). 0 = feasible.
  • medium — service minutes of the requests left unrouted (unassigned_requests_cost); the engine folds it into soft as medium * 10^9.
  • soft — total driving seconds (travel_time_cost).

constraint_info() lists every constraint with its default level and weight; optimaru.pickup_delivery.constraints picks and re-weights them.

The solver is the shared engine in core/optimaru/, with operators registered on top of it whose unit is the request, not the stop. The request moves take requests out of their routes and put each back, pickup and dropoff together, at its cheapest feasible slot pair (request_ruin_recreate), or carry a bundle of requests from one route to another and swap bundles between routes (bundle_moves). A pair move repairs requests whose pair is broken (pair_moves) and a pair ruin kicks whole requests, never half of one (pair_ruin). All are on by default; the switches turn them off to measure what they are worth.

Requests that share a group (Delivery.group_index, DeliveryModel.group) are one job: they ride one vehicle together or all stay unassigned (request_group_cost), and the request moves carry them as one unit.

A vehicle's profile may list requests it may not carry (ProfileRequests, TravelProfile.forbidden_requests; profile_forbidden_request_cost, hard and always on) and requests it is preferred for (TravelProfile.preferred_requests; profile_preferred_request_cost, soft).

optimaru.pickup_delivery.models

JSON request/response contract shared by PDP solver backends.

A route starts at its vehicle's start_depot and ends at its end_depot, or at its last stop when there is none (an open route). Driving seconds and meters come from the vehicle's travel profile (PdpInput.profiles, dicts keyed by depot and stop ids); without one, straight lines between the coordinates. A profile also names the requests its vehicles may not carry (forbidden_requests) and those they are preferred for (preferred_requests).

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 requests it carries.

PdpInput

Bases: StrictModel

PdpRequest

Bases: SolveRequest

The pickup and delivery 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, so every backend reports them identically for the same routes.

to_plan

to_plan(model_input: PdpInput, *, name: str = 'plan') -> _core.PdpRoutePlan

Build the C++ PdpRoutePlan from the pydantic input.

The locations are the depots, then each request's pickup and dropoff, 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 request lists of the profiles the vehicles drive on become ProfileRequests entries, which each vehicle names by profile_requests_index.

vehicle_metrics

vehicle_metrics(plan: PdpRoutePlan, routes: dict[str, list[PdpStop]]) -> 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: PdpInput) -> 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 requests are not here (their cost is always on), nor profile distances (the solution reports driving meters from them, whatever the constraints).

solve_request

solve_request(request: PdpRequest, *, constraints=None) -> PdpSolution

Solve a JSON-friendly request with the metaheuristic backend.

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: PdpRequest, solution: PdpSolution | dict[str, Any]) -> PdpRequest

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 stop ids of its route there, replacing what problem had; a vehicle the solution leaves out starts empty. Vehicles and stops are matched by id.

Stops in no route, the requests in unassigned included, are placed by construction. A solution that routes every request is the exact starting point.

A vehicle's pinned_stops stay fixed input: its route in solution must start with them. Raises ValueError otherwise, on an unknown vehicle, and on whatever the initial routes refuse: an unknown stop, a stop routed twice, or a request whose pickup and dropoff are not together, pickup first. That last one means a hard-infeasible result with a broken pair cannot be used as a starting point.

optimaru.pickup_delivery.constraints

Constraint assembly specs — an API for picking the cost function declaratively.

The default path (Solver(cfg).solve(plan)) enables the seven core PDPTW constraints; the per-vehicle route-policy constraints cost 0 while their parameter is 0. Travel distance, route duration, latency, the enclosing-circle radius and the squared order age 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.pickup_delivery as pdp
from optimaru.pickup_delivery.constraints import (
    PairedRequestCost, TravelTimeCost, UnassignedRequestsCost, VehicleCapacityCost,
    get_constraints,
)

solver = pdp.Solver(cfg)
solver.solve_with_constraints(plan, get_constraints())      # the defaults as-is
solver.solve_with_constraints(plan, [                       # picked
    VehicleCapacityCost(), PairedRequestCost(), UnassignedRequestsCost(),
    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:

  • weight linear multiplier on the constraint cost, in units of its level. None = the C++ component default (pdp.constraint_info() lists them).
  • level None = the default level, otherwise a Level or its name (Level.MEDIUM or "medium"). Any flippable constraint may take any of the three levels. UnassignedRequestsCost is the one medium constraint (folded into the engine's soft level as medium * 10^9): level="hard" charges one hard unit per minute, level="soft" one soft unit per minute, and a weight is in units of the level in effect.
  • exponent sign-preserving power shaping: weight * sign(c) * |c| ** exponent, per vehicle for the route constraints and on the total for the four request-level (global) ones. 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; False shapes c - offset as 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, except RequiredVehicleCost and SquaredOrderAgeCost, which price the requests waiting there and so count the pool as a unit. With an offset it is refused on hard (VehicleCapacityCost by 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 square of every second beyond two hours of driving per vehicle::

solver.solve_with_constraints(plan, [
    *get_constraints(),
    TravelTimeCost(weight=0.001, exponent=2, offset=7200),
])

pdp.constraint_costs(plan, picks) keys the second pick "travel_time_cost#2".

The three coupling constraints (paired_request_cost, same_vehicle_cost, pickup_before_dropoff_cost) are cut so they never overlap — each situation is valued by exactly one term.

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 pdp.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 request-level move/ruin operators read the plan, not the calculator, so they still run. They only propose placements that keep the plan's time windows, capacity and vehicle limits, whatever level a selection scores those on: with one of them soft or left out, the engine's stop moves are what try plans that break it.

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

Bases: Constraint

Load accumulated along the route above vehicle capacity. Default: hard, weight 1.

Goods board at the pickup and leave at the matching dropoff, so what must fit is the peak in between, not the route total. The excess is charged at every node where it persists — exactly like a full recompute.

MaxEndTimeCost dataclass

Bases: Constraint

Minutes (rounded up) by which a stop's service ends after its time window. Default: hard, weight 1.

It uses arrival time + service duration against the stop's max_end_time. The vehicle's own end of shift is VehicleMaxEndTimeCost.

TravelTimeCost dataclass

Bases: Constraint

Driving seconds per vehicle, start depot -> stops (-> 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 -> stops (-> 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

Bases: Constraint

Seconds of driving above the vehicle limit. Default: hard, weight 1.

MaxRouteDurationCost dataclass

Bases: Constraint

Seconds of vehicle working time, waits and service included, above the limit. Default: hard, weight 1.

VehicleMaxEndTimeCost dataclass

Bases: Constraint

Seconds by which the route end passes the vehicle end time. Default: hard, weight 1.

MaxStopsCost dataclass

Bases: Constraint

Pickup/dropoff stops per vehicle above the limit. Default: hard, weight 1.

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 enclosing circle of a route's stops. Default: soft, weight 0 (opt-in).

The depots are excluded; 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

Bases: Constraint

Total route time including waits and service. Default: soft, weight 0 (opt-in).

LatencyCost dataclass

Bases: Constraint

Sum of the times taken to reach each stop. Default: soft, weight 0 (opt-in).

SquaredOrderAgeCost dataclass

Bases: Constraint

Squared seconds from each order to its dropoff finishing. Default: soft, weight 0 (opt-in).

Only dropoffs count, and each request counts on its own, so one very late order costs more than several slightly late ones. An unassigned request is charged as if finished an hour into the plan: otherwise leaving out the oldest orders would be the cheapest thing to do. It is an order age, not lateness past a due time. The square is part of the raw cost, so an exponent compounds it (exponent 2 gives a 4th power).

VehicleFixedCost dataclass

Bases: Constraint

Fixed cost of every vehicle used at least once. Default: soft, weight 1.

PinnedStopsCost dataclass

Bases: Constraint

Routes that do not start with their vehicle's pinned stops. Default: hard, weight 1e12.

Each misplaced stop counts once. Silent for a vehicle that pins nothing. The weight is far above what the other hard constraints total on real input, so no trade between them moves a pinned stop.

RequiredVehicleCost dataclass

Bases: Constraint

Requests off the vehicle they must ride on. Default: hard, weight 1000.

Unassigned counts once and another vehicle twice, so a request with no place on its vehicle waits. Where on the route the request goes stays free.

ProfileForbiddenRequestCost dataclass

Bases: Constraint

Stops of requests carried by a vehicle whose profile forbids them. Default: hard, weight 1000; always on.

TravelProfile.forbidden_requests names the requests a vehicle on the profile may not carry. A forbidden request carried whole costs 2, one unit per stop. Every solve scores this constraint hard, listed or not: on a plan with forbidden requests, 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. Leaving a request unassigned costs only medium, so one that no vehicle may carry waits. Engine-only (no CP-SAT plugin).

ProfilePreferredRequestCost dataclass

Bases: Constraint

Stops of preferred requests on a vehicle whose profile does not prefer them. Default: soft, weight 300.

TravelProfile.preferred_requests names the requests that should go to a vehicle on the profile. A request some vehicle's profile prefers costs one unit per stop on a vehicle whose profile does not prefer it, 2 for the whole request; an unassigned request is left to unassigned_requests_cost. At weight 300 per stop against travel_time_cost's 1 per driving second, a vehicle that does not prefer a request takes it only when that saves more than ten minutes of driving. A request whose vehicles drive on a profile with preferred requests needs this constraint among its constraints (ValueError otherwise); a profile no vehicle drives on prefers nothing. Engine-only (no CP-SAT plugin).

PairedRequestCost dataclass

Bases: Constraint

Requests with only one node on a route. Default: hard, weight 1000.

Half a delivery is worse than none — goods get loaded and never dropped off, or dropped off from nowhere. Structural on the CP-SAT reference (hard only).

SameVehicleCost dataclass

Bases: Constraint

Requests whose pickup and dropoff ride on different vehicles. Default: hard, weight 1000.

Nobody hands goods over midway, so both nodes must travel together. Silent when only one or neither is assigned — paired_request_cost and unassigned_requests_cost value those. Structural on the CP-SAT reference (hard only).

PickupBeforeDropoffCost dataclass

Bases: Constraint

Requests whose dropoff precedes the pickup on the same route. Default: hard, weight 1000.

Only looks at both nodes on the same vehicle — split cases are valued by same_vehicle_cost. Structural on the CP-SAT reference (hard only).

RequestGroupCost dataclass

Bases: Constraint

Grouped requests that are apart from the rest of their group. Default: hard, weight 1000.

The requests of a group are one job: they ride one vehicle together, or all wait. A request is where its pickup is — on a vehicle, or on none. Engine-only (no CP-SAT plugin).

UnassignedRequestsCost dataclass

Bases: Constraint

Service minutes of requests with neither node assigned. Default: medium, weight 1.

Dropping a long job hurts more than dropping a short one. Half-assigned requests are not counted here — paired_request_cost values them at the hard level. 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(), UnassignedRequestsCost(), 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 pdp.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 = pdp.constraint_costs(plan)
score(raw)                     # default set
score(raw, [VehicleCapacityCost(), UnassignedRequestsCost(), 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 pool too for the two constraints that price it; a 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_request_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 requests, and pdp.constraint_costs reports that instance. Unknown names raise ValueError.

The returned value is the engine-level (hard, soft): the medium level (unassigned_requests_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.pickup_delivery._core

Type stubs for optimaru.pickup_delivery._core — the pickup-and-delivery C++ solver.

Times are integer seconds from a common day start. Each vehicle's ordered node_indices (its route) is the decision; a stop in no route is unassigned and lands in unassigned_node_indices.

Score (hard / medium / soft, lexicographic), at the default weights: hard = capacity peak + time-window lateness + the coupling constraints (a request is routed whole, on one vehicle, pickup before dropoff); medium = -(service minutes of unrouted requests), 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.

Score

is_feasible

is_feasible() -> bool

True when hard >= 0: no hard constraint is violated.

Location

index instance-attribute

index: int

Row/column into the driving-time matrix; set by PdpRoutePlan.

Node

One stop: the pickup half or the dropoff half of a request.

delivery_index instance-attribute

delivery_index: int

Index into PdpRoutePlan.deliveries — the request this stop belongs to.

pickup instance-attribute

pickup: bool

True for the pickup half, False for the dropoff half.

vehicle_index instance-attribute

vehicle_index: int

Derived: index of the serving vehicle; -1 == unassigned.

arrival_time instance-attribute

arrival_time: int

Derived: arrival seconds; -1 == unassigned.

Delivery

One transport request: a pickup, a dropoff, and the load between them.

demand instance-attribute

demand: int

Added to the vehicle's load at the pickup, removed at the dropoff.

order_time instance-attribute

order_time: int

When the request was placed, in plan seconds; negative if it was already waiting when the plan starts.

required_vehicle_index instance-attribute

required_vehicle_index: int

Index into PdpRoutePlan.vehicles of the vehicle this request must ride on; -1 == any.

group_index instance-attribute

group_index: int

The group this request travels in; -1 == none. The requests that share a group ride one vehicle together, or all wait (request_group_cost).

ProfileRequests

What one kind of vehicle may carry: the requests it may not (profile_forbidden_request_cost) and those it is preferred for (profile_preferred_request_cost). A vehicle names its entry with Vehicle.profile_requests_index. Both lists hold indices into PdpRoutePlan.deliveries in strictly increasing order, none in both.

Vehicle

capacity instance-attribute

capacity: int

Maximum load carried at any one moment, not a route total.

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_requests_index instance-attribute

profile_requests_index: int

Which entry of PdpRoutePlan.profile_requests says what the vehicle may carry; -1 (the default) for none.

pinned_node_indices instance-attribute

pinned_node_indices: list[int]

node_indices is the decision: the ordered route (indices into nodes).

PdpRoutePlan

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_requests lists what each kind of vehicle may not carry or is preferred for (ValueError for an index out of range, a list out of order, a request in both lists, a required vehicle whose profile forbids the request).

unassigned_node_indices instance-attribute

unassigned_node_indices: list[int]

The unassigned pool. A request is dropped when BOTH its stops are here; exactly one here is a half-assigned request, which is hard-infeasible.

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.

routes

routes() -> dict[str, list[str]]

Vehicle id -> ordered stop ids (convenience view).

unassigned_delivery_ids

unassigned_delivery_ids() -> list[str]

Ids of the requests left entirely unrouted.

rebuild_unassigned_pool

rebuild_unassigned_pool() -> None

Recompute unassigned_node_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 order: tightest window / largest demand first.

pair_construction_heuristic instance-attribute

pair_construction_heuristic: bool

Cheapest feasible insertion of complete pickup/dropoff pairs.

late_acceptance_size instance-attribute

late_acceptance_size: int

LATE_ACCEPTANCE: 0 = auto: clamp(4 * len(nodes), 200, 1600) up to 60 nodes, 5 above.

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 requests.

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 requests (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 request) 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.

pair_exchange_min_nodes instance-attribute

pair_exchange_min_nodes: int

Minimum node count for pair exchange; 0 forces it at every size.

pair_assignment_probability instance-attribute

pair_assignment_probability: float

Share of pair moves that drop a request into the pool or pull one back out — how the medium level is reachable at all.

pair_ruin instance-attribute

pair_ruin: bool

Ruin whole requests, never half of one.

request_ruin_recreate instance-attribute

request_ruin_recreate: bool

Take a few requests out of their routes and reinsert each, pickup and dropoff together, at its cheapest feasible slot pair (in random order or by regret_k, with blink_rate). Requests waiting unassigned join the reinsertion.

request_ruin_max_requests instance-attribute

request_ruin_max_requests: int

The most requests one application takes out (1 = a pair relocate with the best slot). Never more than two fifths of the plan's requests; a request of a group brings its whole group, which can take the count past that.

bundle_moves instance-attribute

bundle_moves: bool

Move requests whose pickups follow each other on a route to another route together, or swap two such bundles between nearby routes.

bundle_max_requests instance-attribute

bundle_max_requests: int

The most requests in one bundle, a group counting as one.

ruin_recreate_rewards instance-attribute

ruin_recreate_rewards: list[float]

Four rewards, indexed NEW_BEST / BETTER / ACCEPTED / REJECTED.

regret_k instance-attribute

regret_k: int

Repair strategy: >= 2 uses regret-k insertion, 0/1 plain greedy.

on_new_best instance-attribute

on_new_best: Callable[[int, Score], None] | None

Called with (step, score) on each new best, in the levels of the final plan.score.

Solver

Construction heuristic + local search + adaptive ruin & recreate, with request-level move and ruin operators. Solves IN PLACE: fills vehicle.node_indices, the unassigned pool, the derived fields and plan.score.

solve

solve(plan: PdpRoutePlan) -> None

Solve on the seven core constraints, or on the default constraints when two requests or more share a group or a profile lists requests (request_group_cost and the two profile request costs are not core constraints; every parallel start then has a set of its own). The core constraints do not include required_vehicle_cost, pinned_stops_cost or the vehicle limits either: for a plan without groups that uses any of those, call solve_with_constraints.

solve_with_constraints

solve_with_constraints(plan: PdpRoutePlan, constraints: Iterable[Any] | None = ...) -> None

Score the same solve with a caller-chosen constraint set (see optimaru.pickup_delivery.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. plan.score and on_new_best report the three levels unfolded, so a soft total of 10^9 or more stays soft. With parallel_solver_count above 1 every start is scored by its own copy of the picks. profile_forbidden_request_cost is always on: a plan with forbidden requests 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 requests needs profile_preferred_request_cost in the list: ValueError otherwise.

ConstraintInfo

Bases: NamedTuple

One constraint-catalog row, read off the C++ default assembly.

calculate_score

calculate_score(plan: PdpRoutePlan) -> Score

Recompute the derived fields and the score (also stores plan.score).

The score is the one solve(plan) stores: the seven core constraints, or the default constraints when the plan has a group of two or more requests or a profile request list.

build_random_instance

build_random_instance(request_count: int, vehicle_count: int, seed: int = 0) -> PdpRoutePlan

A randomly generated PDPTW instance, for demos and benchmarks.

list_constraints

list_constraints() -> list[str]

Constraint names scored by this domain (default assembly order, snake_case): the nineteen per-vehicle constraints (vehicle_capacity_cost ... required_vehicle_cost, profile_forbidden_request_cost, profile_preferred_request_cost), then the five request-level globals (paired_request_cost, same_vehicle_cost, pickup_before_dropoff_cost, request_group_cost, unassigned_requests_cost). The same names optimaru.pickup_delivery.constraints uses.

constraint_costs

constraint_costs(plan: PdpRoutePlan, 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 unit); a global constraint reports one cost. optimaru.pickup_delivery.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_request_cost on a plan with forbidden requests, which every solve scores), each entry carrying its pick's knobs, the k-th pick of a name keyed "#" from the second on. "units" (the per-vehicle constraints) lists the vehicle indices the constraint evaluates, so the literal offset (clip=False) charges every vehicle, an idle one included, and not the pool; required_vehicle_cost and squared_order_age_cost price the pool too and carry no "units" (every unit counts). The medium fold belongs to the domain, so EVERY entry carries it.

constraint_info

constraint_info() -> list[ConstraintInfo]

The constraint catalog, in list_constraints() order: the default level and weight of each constraint (unassigned_requests_cost is medium at weight 1 in medium units; pinned_stops_cost hard at 1e12; the coupling constraints, required_vehicle_cost and request_group_cost hard at 1000). 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, squared_order_age_cost).