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, Warehouse, 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.
The layout is the solution's warehouse: a grid of shelvings of any size (by default
5 columns x 3 shelving rows), or named locations with a walking-distance table
(Warehouse.from_distances).
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}
The layout is part of the request, in one of two kinds:
- a grid of shelvings (the default). A location is a
LocationModel: the column letters (A, B, ..., Z, AA, ... as spreadsheets write columns) + the shelving row 1.. (the id "(A,1)"), a side (LEFT/RIGHT) and a row 0..shelving_height within the shelving.warehouse(WarehouseModel) gives the size of the grid; without it, 5 columns (A..E) x 3 shelving rows of shelvings 2 m wide and 10 m tall, 3 m apart. -
named locations with a walking-distance table:
locationslists the ids anddistancesthe meters from one to another, and everylocationof a trolley or an order item is then one of those ids::OrderPickingRequest( locations=["dock", "aisle-1", "aisle-2"], distances={"dock": {"aisle-1": 12, "aisle-2": 20}, "aisle-1": {"aisle-2": 9}}, trolleys=[TrolleyModel(id="1", bucket_count=4, bucket_capacity=48000, location="dock")], orders=[OrderModel(id="order1", items=[ProductModel(id="p0", volume=1232, location="aisle-2")])], )
One request uses one kind: a grid location in a request with locations, or an id in
one without, is refused.
LocationModel ¶
Bases: StrictModel
A location of a grid warehouse: shelving (column, row), side and in-shelving row.
Whether it is inside the grid is the request's to check, which knows the grid's size
(OrderPickingRequest.warehouse; by default columns A..E, shelving rows 1..3, rows 0..10).
WarehouseModel ¶
Bases: StrictModel
The size of a grid warehouse. Every field defaults to the grid a request without one gets.
column_count columns (A, B, ...) by shelving_row_count rows (1, 2, ...) of shelvings, each
shelving_width wide and shelving_height tall, shelving_padding meters of corridor between
neighbors, all in whole meters. A shelving side holds the rows 0..shelving_height.
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).
The layout is a grid unless locations and distances are given (see the module docstring):
warehouse sizes the grid, and a request without it has the default one.
to_solution ¶
to_solution(request: OrderPickingRequest) -> _core.OrderPickingSolution
Build the C++ OrderPickingSolution from the pydantic request: its warehouse, 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. The layout (warehouse, or locations and distances) is not one
either: the response reports the meters walked from it whatever the constraints. 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 custom_moves.order_consolidate
(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.
The layout is the solution's warehouse: a grid of shelvings of any size (the default:
5 columns x 3 shelving rows), or named locations with a walking-distance table.
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.
On a grid: the shelving (column 0.. == A.., shelving_row 0.. == rows 1..), its side and
the row 0..shelving_height within the shelving side. The constructor makes one of
these; whether it is inside the grid is checked where the warehouse is known
(OrderPickingSolution, Solver.solve).
In a warehouse of named locations: one of them, from Warehouse.location(id). It belongs
to that warehouse: a solution of another warehouse refuses it (ValueError).
Warehouse ¶
The layout of a warehouse: a grid of shelvings, or named locations.
Warehouse() is the default grid: 5 columns (A..E) x 3 shelving rows (1..3) of shelvings
2 m wide and 10 m tall, 3 m of corridor between neighbors. The arguments size another
one, in whole meters: column_count 1..18278, shelving_row_count 1..10000, and
shelving_width, shelving_height, shelving_padding 1..1000 each (ValueError
outside). A shelving side holds the rows 0..shelving_height.
Warehouse.from_distances(location_ids, distances) is a warehouse of named locations.
MAX_SHELVING_SIZE
instance-attribute
¶
MAX_SHELVING_SIZE: int
1000: the most meters of shelving_width, shelving_height and shelving_padding.
MAX_DISTANCE
instance-attribute
¶
MAX_DISTANCE: int
1000000: the longest distance, in meters, a table of named locations may hold.
MAX_LOCATIONS
instance-attribute
¶
MAX_LOCATIONS: int
4096: the most named locations of a warehouse.
from_distances
staticmethod
¶
from_distances(location_ids: list[str], distances: list[list[int]]) -> Warehouse
A warehouse of named locations: distances[i][j] is the whole meters from
location_ids[i] to location_ids[j].
The table is square over the ids (at most 4096) and may be asymmetric. ValueError for a repeated id, a distance outside 0..1000000 or a location that is not 0 from itself.
location ¶
location(id: str) -> WarehouseLocation
The named location with this id (ValueError: unknown id, or a grid).
location_id ¶
location_id(location: WarehouseLocation) -> str
What the location is called: the id of a named location, the shelving id of a grid one.
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.
__init__ ¶
__init__(orders: list[Order], trolleys: list[Trolley], pick_tasks: list[PickTask], warehouse: Warehouse | None = None) -> None
warehouse is the layout the locations are in; None is the default grid.
ValueError when a trolley or a pick task is at a location outside it: beyond the grid, or a grid location in a warehouse of named locations (and the reverse).
SolverConfig ¶
The solver settings, by stage of the solve: stop, perturbation, custom_moves, moves, selection, acceptance, ruin_recreate, run.
Read and write a setting as config.<group>.<name>, or give whole groups when making it:
SolverConfig(stop={"time_limit_seconds": 10}). See optimaru._config.
perturbation
instance-attribute
¶
perturbation: Perturbation
When a stalled search is kicked, and the kick: a large ruin & recreate taken whatever it scores.
custom_moves
instance-attribute
¶
custom_moves: CustomMoves
A step's move, next: this use case's own moves, chosen adaptively on their share of steps.
moves
instance-attribute
¶
moves: Moves
A step's move, otherwise: the move mix, by relative weight (0 turns a move off).
selection
instance-attribute
¶
selection: Selection
What the move mix moves: nearby candidates and this use case's hints.
acceptance
instance-attribute
¶
acceptance: Acceptance
Whether the candidate becomes the current solution.
ruin_recreate
instance-attribute
¶
ruin_recreate: RuinRecreate
The ruin operators, their adaptive selection and the repair, shared by the kick and the strategies that ruin.
Stop ¶
config.stop: When the search stops: the first limit reached.
Perturbation ¶
config.perturbation: When a stalled search is kicked, and the kick: a large ruin & recreate taken whatever it scores.
CustomMoves ¶
config.custom_moves: A step's move, next: this use case's own moves, chosen adaptively on their share of steps.
Moves ¶
config.moves: A step's move, otherwise: the move mix, by relative weight (0 turns a move off).
Selection ¶
config.selection: What the move mix moves: nearby candidates and this use case's hints.
Acceptance ¶
config.acceptance: Whether the candidate becomes the current solution.
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
0 = auto: clamp(4 * pick task count, 200, 1600).
RuinRecreate ¶
config.ruin_recreate: The ruin operators, their adaptive selection and the repair, shared by the kick and the strategies that ruin.
Run ¶
config.run: Seeds, parallel starts and debugging aids.
to_dict ¶
to_dict() -> dict[str, dict[str, object]]
Every setting by group and name: the shape of a request's solver_parameters.
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.
The solution is the solve's own while it runs (it also keeps its table of distances on it, and on a grid numbers the locations, both removed at the end): do not read, copy, score or solve the same solution object from another thread meanwhile.
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, warehouse: Warehouse | None = None) -> int
Distance in meters between two locations of warehouse (None: the default grid).
ValueError when one of them is not a location of it (outside the grid, or not one of its named locations).
distance_to_travel ¶
distance_to_travel(solution: OrderPickingSolution, trolley_index: int) -> int
One trolley's round-trip distance.
Like calculate_score and constraint_costs, it first checks every location against the
solution's warehouse (ValueError), since a location can be replaced after the solution
was made.
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).