optimaru.order_picking¶
Generated from the sources of optimaru/order_picking/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.order_picking ¶
Order picking — C++ core with Python helpers.
Side, WarehouseLocation, Order, PickTask, Trolley,
OrderPickingSolution, Score, ConstraintInfo, Solver, SolverConfig
and the module functions come from the compiled C++ core (_core). Each
trolley's ordered pick_task_indices list is the decision; trolley_index /
previous_pick_task / next_pick_task on a pick task are derived from the
lists.
Score convention (hard / soft), at the default weights:
hard = -(missing trolley buckets) # trolley_capacity_cost
soft = -(travel distance in meters # distance_from_previous_pick_task_cost
# + distance_from_last_pick_task_to_path_origin_cost
+ 1000 x per-order distinct-trolley count) # order_split_by_trolley_cost
hard 0 == feasible. constraint_costs(solution) gives every constraint's raw
per-trolley cost (the only per-constraint surface), constraint_info() every
constraint with its default level and weight; change one through a constraint
selection (see optimaru.order_picking.constraints).
Quick start::
import optimaru.order_picking as op
solution = op.generate_demo_data() # the demo warehouse
solution = op.solve(solution, time_limit_seconds=5.0, random_seed=0)
print(solution.score, solution.routes())
pydantic request/response models (JSON in/out) live in
optimaru.order_picking.models.
optimaru.order_picking.models ¶
Pydantic request/response models for the order-picking solver.
JSON-friendly in/out (snake_case fields, PascalCase classes), same pattern as
optimaru.vehicle_routing.models:
from optimaru.order_picking.models import (LocationModel, OrderModel,
OrderPickingRequest, ProductModel,
TrolleyModel, solve_request)
request = OrderPickingRequest(
time_limit_seconds=2,
trolleys=[TrolleyModel(id="1", bucket_count=4, bucket_capacity=48000,
location=LocationModel(column="A", shelving_row=1,
side="LEFT", row=0))],
orders=[OrderModel(id="order1", items=[
ProductModel(id="p0", name="Milk Brick", volume=1232,
location=LocationModel(column="D", shelving_row=1,
side="RIGHT", row=4)),
])],
)
solution = solve_request(request)
print(solution.routes) # {"1": [stops...]}
print(solution.distance_by_trolley) # {"1": meters}
A shelving is addressed by column letter A..E + shelving row 1..3 (the id "(A,1)"), a side (LEFT/RIGHT) and a row 0..10 within the shelving.
LocationModel ¶
Bases: StrictModel
A warehouse location: shelving (column, row), side and in-shelving row.
ProductModel ¶
Bases: StrictModel
One order item: an indivisible product at a warehouse location.
OrderPickingRequest ¶
Bases: SolveRequest
The trolleys and orders with the settings of one solve (see SolveRequest for those).
to_solution ¶
to_solution(request: OrderPickingRequest) -> _core.OrderPickingSolution
Build the C++ OrderPickingSolution from the pydantic request: one
Order per OrderModel and one PickTask per order item (ids "
parameter_uses ¶
parameter_uses(request: OrderPickingRequest) -> list[ParameterUse]
The parameters request sets away from their defaults that act only through a cost.
None here: every field that a cost reads is required (bucket count and capacity,
volumes, locations), so none has a default to leave it off, and initial_route is a
starting point. Kept so solve_request checks this use case as it checks the others;
the table is "Parameters and their costs" in docs/use-cases/README.md.
solve_request ¶
solve_request(request: OrderPickingRequest, *, constraints=None) -> OrderPickingResponse
Solve the request and shape the response (routes per trolley plus the per-trolley travel distance).
A parameter set away from its default whose costs the constraints leave out would be
refused with ValueError (parameter_uses, empty for this use case).
with_initial_solution ¶
with_initial_solution(problem: OrderPickingRequest, solution: OrderPickingResponse | dict[str, Any]) -> OrderPickingRequest
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 trolley's initial_route becomes the pick task ids of its route
there, replacing what problem had; a trolley the solution leaves out
starts empty. Trolleys and pick tasks are matched by id.
A pick task id is "order.items: reorder an order's items and the same id names
a different item. Keep the order as it was when solution was solved.
Tasks in no route are placed by construction. A solution that routes every task is the exact starting point. Raises ValueError on an unknown trolley or pick task, or a task routed twice.
optimaru.order_picking.constraints ¶
Constraint assembly specs — an API for picking the cost function declaratively.
The default path (op.solve(solution)) enables all four constraints at their default
weights. This module is the alternative path next to it: pick constraints, change weights,
change levels, shape the cost, and pass the list to solve(solution, constraints=...).
A constraint list reads one way: one class call per constraint::
import optimaru.order_picking as op
from optimaru.order_picking.constraints import (
DistanceFromLastPickTaskToPathOriginCost, DistanceFromPreviousPickTaskCost,
OrderSplitByTrolleyCost, TrolleyCapacityCost, get_constraints,
)
op.solve(solution, constraints=get_constraints()) # the defaults as-is
op.solve(solution, constraints=[ # picked
TrolleyCapacityCost(), OrderSplitByTrolleyCost(weight=100),
])
Only listed constraints are scored — leave one out and its term disappears from the
score. (The module also carries ready-made default instances: trolley_capacity_cost
is TrolleyCapacityCost(), and so on.)
Every spec takes five knobs:
weightlinear multiplier on the constraint cost.None= the component default (OrderSplitByTrolleyCost 1000, the other three 1);op.constraint_info()reports the defaults.levelNone= the default level, otherwiseLevel.HARDorLevel.SOFT(or the names"hard"and"soft"). This use case has no medium level:level="medium"raises ValueError.exponentsign-preserving power shaping per trolley:weight * sign(c) * |c| ** exponent. 2.0 = squared, so concentrated violations grow much costlier.offset(keyword) shifts that shaping per trolley; 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 trolley below the offset — an empty one (cost 0) included — lowers the penalty. With an offset it is refused on hard (TrolleyCapacityCostby 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. The walk plus the square of every meter beyond 100 m per trolley::
op.solve(solution, constraints=[
TrolleyCapacityCost(),
DistanceFromPreviousPickTaskCost(),
DistanceFromPreviousPickTaskCost(weight=0.1, exponent=2, offset=100),
DistanceFromLastPickTaskToPathOriginCost(),
OrderSplitByTrolleyCost(),
])
op.constraint_costs(solution, picks) keys the second pick
"distance_from_previous_pick_task_cost#2".
Names (name) are the C++ component names in snake_case
(TrolleyCapacityCost -> trolley_capacity_cost). The core derives them
mechanically, so there is no hand-maintained alias table — check them with
op.list_constraints(). Module-level instance names use the same snake_case,
so they match the strings list_constraints() prints.
Two knobs do not apply on the plugin path: parallel_solver_count
(a caller-owned calculator cannot be cloned into workers) and order_consolidate_moves
(that operator reads the monolithic calculator's live volume table). Details are in
the comments of cpp/op/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.
TrolleyCapacityCost
dataclass
¶
Bases: Constraint
Buckets a trolley is short of. Default: hard, weight 1.
Orders never share buckets, so bucket counts round up the volume of each order on the trolley — that rounding is exactly why splitting an order over several trolleys wastes capacity.
DistanceFromPreviousPickTaskCost
dataclass
¶
Bases: Constraint
Travel distance from each pick to the next. Default: soft, weight 1.
For the first pick, the trolley's parking spot stands in as the "previous location".
DistanceFromLastPickTaskToPathOriginCost
dataclass
¶
Bases: Constraint
Distance from the last pick back to the starting point. Default: soft, weight 1.
An empty trolley never leaves, so it costs nothing.
OrderSplitByTrolleyCost
dataclass
¶
Bases: Constraint
Number of (order, trolley) pairs. Default: soft, weight 1000.
An order shared by three trolleys costs three times one carried by a single trolley. Deliberately expensive relative to the distance terms — orders arriving in pieces become a packing problem downstream. Unlike the other constraints the raw cost is never 0 while picks are assigned: an order carried whole by one trolley still counts 1.
get_constraints ¶
get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]
Return the cost function. Without arguments, all four default constraints.
When constraints is given, that list is used as-is — only the listed
constraints are scored::
get_constraints([TrolleyCapacityCost(), OrderSplitByTrolleyCost(weight=100)])
Same contract as the C++ applyConstraints: an empty list is an error (a filter that came out empty must not silently flip to "score everything"); 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 op.constraint_costs(solution) returns: per constraint, the
raw cost of each trolley (before weight, exponent, offset and level
rounding). Fetch it once and rescore with different weights without re-solving::
raw = op.constraint_costs(solution)
score(raw) # default set
score(raw, [TrolleyCapacityCost(), OrderSplitByTrolleyCost(weight=100)])
score(raw, [OrderSplitByTrolleyCost(), OrderSplitByTrolleyCost(weight=500, offset=2)])
No solver and no search are involved. The arithmetic matches the engine —
each trolley 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. Unknown names raise ValueError.
optimaru.order_picking._core ¶
Type stubs for optimaru.order_picking._core — the order-picking C++ solver.
Each trolley's ordered pick_task_indices is the decision; a pick task in
no list is unassigned. trolley_index / previous_pick_task /
next_pick_task on a pick task are derived from the lists.
Score (hard / soft, lexicographic), at the default weights: hard = -(missing trolley buckets) # trolley_capacity_cost soft = -(walk to and between the picks, m # distance_from_previous_pick_task_cost + walk back to the trolley origin, m # distance_from_last_pick_task_to_path_origin_cost + 1000 x (order, trolley) pairs) # order_split_by_trolley_cost
Side ¶
Shelving side: LEFT or RIGHT.
WarehouseLocation ¶
A spot in the warehouse: shelving (column 0..4 == A..E, shelving_row 0..2 == rows 1..3), side and the row 0..10 within the shelving side.
PickTask ¶
The picking of one order item: an element of a trolley's pick list.
trolley_index
instance-attribute
¶
trolley_index: int
Derived: index of the owning trolley; -1 == unassigned.
previous_pick_task
instance-attribute
¶
previous_pick_task: int
Derived: previous pick in the trolley's list; -1 == none.
next_pick_task
instance-attribute
¶
next_pick_task: int
Derived: next pick in the trolley's list; -1 == none.
Trolley ¶
pick_task_indices
instance-attribute
¶
pick_task_indices: list[int]
The decision: ordered indices into pick_tasks.
OrderPickingSolution ¶
The problem data plus the trolleys' pick lists and the score.
SolverConfig ¶
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
0 = auto: clamp(4 * pick task count, 200, 1600).
Solver ¶
solve ¶
solve(solution: OrderPickingSolution) -> None
Solve in place: mutates pick_task_indices, refreshes the derived variables and stores the best score in solution.score.
solve_with_constraints ¶
solve_with_constraints(solution: OrderPickingSolution, constraints: Iterable[Any] | None = ...) -> None
Same solve, scored by a caller-chosen constraint set (see
optimaru.order_picking.constraints). The picks replace the defaults; None
keeps them. A name may be picked several times: each pick is its own
instance with its own knobs, and the instances add up.
ConstraintInfo ¶
Bases: NamedTuple
One constraint-catalog row, read off the C++ default assembly.
calculate_distance ¶
calculate_distance(start: WarehouseLocation, end: WarehouseLocation) -> int
Distance in meters between two locations.
distance_to_travel ¶
distance_to_travel(solution: OrderPickingSolution, trolley_index: int) -> int
One trolley's round-trip distance.
update_shadow_variables ¶
update_shadow_variables(solution: OrderPickingSolution) -> None
Re-derive the pick tasks' derived fields from the pick lists.
calculate_score ¶
calculate_score(solution: OrderPickingSolution) -> Score
Refresh the derived fields, recompute and store solution.score.
generate_demo_data ¶
generate_demo_data(trolleys_count: int = 5, bucket_count: int = 4, bucket_capacity: int = 48000, orders_count: int = 8, random_seed: int = 37) -> OrderPickingSolution
The demo warehouse (deterministic for a given random_seed).
list_constraints ¶
list_constraints() -> list[str]
Constraint names scored by this domain (default assembly order, snake_case):
trolley_capacity_cost, distance_from_previous_pick_task_cost,
distance_from_last_pick_task_to_path_origin_cost, order_split_by_trolley_cost.
The same names optimaru.order_picking.constraints uses.
constraint_costs ¶
constraint_costs(solution: OrderPickingSolution, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]
Raw per-trolley cost of every constraint, before weight/exponent/offset/level:
{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}}, one cost per trolley (every
trolley is evaluated, an empty one included). None = the default constraints; a
pick list (as for solve) scores exactly those picks, each entry carrying its pick's
knobs, the k-th pick of a name keyed "optimaru.order_picking.constraints.score() turns it into a score. The only
per-constraint surface: the travel distance is the sum of the two distance
entries' costs, the (order, trolley) pair count the sum of
order_split_by_trolley_cost's.
constraint_info ¶
constraint_info() -> list[ConstraintInfo]
The constraint catalog, in list_constraints() order: trolley_capacity_cost (hard, 1), distance_from_previous_pick_task_cost (soft, 1), distance_from_last_pick_task_to_path_origin_cost (soft, 1), order_split_by_trolley_cost (soft, 1000); all flippable, none a reward, all scored by default (default_enabled).