optimaru.container_loading¶
Generated from the sources of optimaru/container_loading/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.container_loading ¶
Container loading — Python wrapper of the C++ solver on the optimaru engine.
Three-dimensional loading of boxes into containers: pallets, rack bays, a vehicle's cargo
space, shipping cartons. The decision is an order: every container has a list of items,
its loading order (Container.items, item indices). Where each item then stands is
derived from that order by a placement decoder, so positions are outputs:
Item.container, x, y, z and the placed size.
Score, at the default weights (1 each; the three opt-in costs at 0):
hard = -(items that found no place # unplaced_item_cost
+ weight above a container's max_weight # container_weight_cost
+ weight on an item above max_load_on_top # stacking_load_cost
+ stacking rules and layer limits broken # stacking_rule_cost
+ items blocking one that leaves earlier # unloading_order_cost
+ centre of gravity beyond its limits # balance_limit_cost
+ pairs a segregation rule keeps apart # segregation_cost
+ axle loads above their limits # axle_load_cost
+ all-or-none groups loaded in part # incomplete_group_cost
+ one-container groups in several) # single_container_cost
(an unplaced item counts its priority, an optional one in optional_item_cost)
soft = -(cost of the containers in use # used_container_cost
+ optional items left out # optional_item_cost
+ containers a group is in beyond its first) # group_split_cost
(+ used_length_cost, load_balance_cost, shipping_cost when given a weight)
hard 0 == feasible. The problem carries no weights: change one through a constraint
selection (see optimaru.container_loading.constraints). constraint_info() lists every
constraint with its default level and weight.
Basic usage::
import optimaru.container_loading as cl
problem = cl.ContainerLoadingProblem(
containers=[cl.Container("pallet-1", 1200, 800, 1500), cl.Container("pallet-2", 1200, 800, 1500)],
items=[cl.Item(f"box-{i}", 400, 300, 300, weight=6000) for i in range(30)],
)
cl.solve(problem, time_limit_seconds=2.0, random_seed=0)
print(problem.score, problem.containers_used())
for item in problem.items:
print(item.id, item.container, (item.x, item.y, item.z))
problem.items and problem.containers return copies: write loading orders with
problem.set_loading([...]). The JSON contract is optimaru.container_loading.models
(pydantic).
optimaru.container_loading.models ¶
Pydantic JSON contract for the container-loading domain.
The problem as JSON, mirroring _core's Container / Item / ContainerLoadingProblem::
from optimaru.container_loading.models import ContainerLoadingProblemModel
model = ContainerLoadingProblemModel.model_validate(data) # JSON -> pydantic
solved = cl.solve(model, time_limit_seconds=5.0) # a new, solved model
for item in solved.items:
print(item.id, item.container, item.x, item.y, item.z)
Lengths and weights are whole numbers in the caller's unit (the guide's examples use mm
and g). Coordinates: x runs along the container's length (0 = the closed end, the
door is at x = length), y along its width, z up. An item's x, y, z is
its corner nearest the origin, placed_length, placed_width, placed_height its size
along x, y and z after rotation.
The problem carries no constraint weights (extra="forbid"): weights come only from
constraint selections, and the defaults are the C++ components'
(container_loading.constraint_info()).
ItemModel ¶
Bases: StrictModel
One box. The fields from container on are outputs: a solve fills them in.
AxleGroupModel ¶
Bases: StrictModel
One axle group of the vehicle a container is the cargo space of.
AxleLoadModel ¶
Bases: StrictModel
Output: the axle loads of a container at one stage of its route.
UnloadingViolationModel ¶
Bases: StrictModel
One unloading pair left: item (it leaves later) stands in the way of blocks.
ContainerInstanceModel ¶
Bases: StrictModel
Output: one used container of a type listed with a quantity other than 1.
RateBreakModel ¶
Bases: StrictModel
One weight break of a rate table: a container billed at most max_weight costs price to ship.
RateTableModel ¶
Bases: StrictModel
What one used container costs to ship, by its billed weight: the price of the first break
whose max_weight is at least the billed weight.
ContainerModel ¶
Bases: StrictModel
One physical space: a pallet, a rack bay, a cargo space, one carton.
The fields from items on are outputs: a solve fills them in.
instance_orders ¶
instance_orders() -> list[list[str]]
For a quantity other than 1: the loading order of each container a solve goes in with,
from instances when a solve has filled them in, else from initial_instances.
loading_order ¶
loading_order() -> list[str]
The loading order this container goes into a solve with: items (and the
unplaced_items after them) when a solve has filled them in, else initial_items.
Where an unplaced item stood in the order is not kept: it is tried again after the placed ones, which stand where they stood. So a solved model in which everything is placed is exactly the solution it was; one with unplaced items can only come back with fewer of them, though not necessarily with a lower hard score: an item placed now may stand on a fragile item or in front of an earlier stop.
StopZoneModel ¶
Bases: StrictModel
One stop's zone along every container's length (see the problem's stop_zones).
StackingRuleModel ¶
Bases: StrictModel
Items whose stack_group is top may not stand on items whose stack_group is bottom.
SegregationRuleModel ¶
Bases: StrictModel
Items of classes a and b (the same class when equal) kept apart: in different containers,
or, with a distance, at least that far apart in the floor plane.
GroupRuleModel ¶
Bases: StrictModel
How the items whose group is id are loaded. A rule with both flags false does nothing.
ContainerLoadingProblemModel ¶
Bases: StrictModel
The containers and the items to load into them. The score fields, containers_used
and unplaced_items are outputs.
validate_rates ¶
validate_rates() -> ContainerLoadingProblemModel
One rate table per zone, breaks ascending, and a table for every container's zone (the engine's checks; it also refuses a billed weight that can pass a table's top break).
copies ¶
copies() -> list[tuple[ContainerModel, str, list[str]]]
The containers the engine gets: (type, id, loading order) for each. A type of quantity 1 is
itself; one of quantity n is n containers "id#1" .. "id#n" (no more than there are items);
one of quantity None as many as needed_copies says.
needed_copies ¶
needed_copies(container: ContainerModel) -> int
How many containers a type of quantity None gets: twice the containers the volume of the items that fit it needs, or twice those their weight needs against its max_weight, whichever is more, plus one; at least the items that cannot share a container with any other (in every orientation their rotations allow, more than half the container along every axis); at most one per item that fits, and at most MAX_QUANTITY. A rule of thumb, not a guarantee: give a quantity where unplaced items show it is short.
to_core ¶
to_core() -> _core.ContainerLoadingProblem
pydantic -> engine object. Each container's list is its loading_order(): what a
solve filled in when there is one, else initial_items. A type with a quantity other
than 1 becomes its copies(), each tagged with the type's id too. The other outputs
are ignored; the engine derives them again.
The engine object starts with the default weights for what its decoder weighs when an
item can only break an order or a limit (the weights of a solve's constraints are not
part of the model). A model solved under other constraints is placed again as that
solve placed it by a solve of no steps with the same constraints
(cl.solve(model, time_limit_seconds=0, constraints=...)), not by calculate_score.
from_core
classmethod
¶
from_core(problem: ContainerLoadingProblem) -> ContainerLoadingProblemModel
engine object -> pydantic, with the outputs.
It decodes problem first (update_placements), so the positions and the
per-container outputs describe the loading orders the problem holds now, solved or
not, and to_core() gives those orders back. The score fields are problem.score
as a solve or calculate_score last set it (under a constraint selection: the
selection's score). initial_items is left empty: the lists are in items.
ContainerLoadingRequest ¶
Bases: SolveRequest
The container-loading problem with the settings of one solve (see SolveRequest for those).
solved_model ¶
solved_model(problem: ContainerLoadingProblemModel, core: ContainerLoadingProblem) -> ContainerLoadingProblemModel
The solved model of problem, from core, the engine object problem.to_core() gave and a
solve has filled in: a type of quantity 1 as from_core reports it, one with another quantity
with its used containers in instances, numbered "initial_items, initial_instances,
quantity) as problem has them.
parameter_uses ¶
parameter_uses(problem: ContainerLoadingProblemModel) -> list[ParameterUse]
The parameters problem sets away from their defaults that act only through a cost.
solve refuses a model whose selection holds none of a parameter's costs
(optimaru._constraint.require_costs); the table is "Parameters and their costs" in
docs/use-cases/README.md. The sizes and min_support_ratio are read by the decoder,
whatever the selection, and so are bottom_only and max_stack_height; cost is
used_container_cost's own scale. optional needs optional_item_cost although it also
changes what unplaced_item_cost and container_weight_cost count and what the decoder leaves
out: without the cost an optional item left out would count nowhere (pick it at weight 0
to mean that). allowed_containers and tags are the decoder's.
with_initial_solution ¶
with_initial_solution(problem, solution)
Return a copy of problem whose search starts from solution.
solution is a solved problem model or a dict of the same shape. Containers and items
are matched by id: each container's initial_items becomes the items it has in the
solution (its placed items, in loading order), replacing what problem had; a type with a
quantity other than 1 takes its instances' items as initial_instances (those beyond its
quantity are left out, and their items constructed again). A container whose quantity
changed between the two is carried over in the problem's shape: a single container takes
the instances' orders one after the other, a type a single container's order as its first
instance. A container the solution leaves out starts empty. Only the placed items are taken
(a type's instances' too); the unplaced ones are constructed again, where solve(solved)
loads them back after the placed ones. Items the solution placed nowhere are constructed
around the seeded loading orders before the search starts. The copy carries no outputs.
Raises ValueError on an unknown container or item, or an item listed twice.
solve_request ¶
solve_request(request: ContainerLoadingRequest, *, constraints=None) -> ContainerLoadingProblemModel
Solve a pydantic request and return the solved problem model.
This is solve(request.model_input, ...) with the request's settings as the keywords
of the same names (see SolveRequest), and constraints the selection solve
takes. The request is not changed.
optimaru.container_loading.constraints ¶
Constraint assembly specs — an API for picking the cost function declaratively.
The default path (cl.solve(problem)) scores all seventeen constraints at their default
weights, three of them opt-in at weight 0. This module is how a call changes that: pick
constraints, change weights, change levels, shape the cost, and pass the list to
solve(problem, constraints=...).
A constraint list reads one way: one class call per constraint::
import optimaru.container_loading as cl
from optimaru.container_loading.constraints import (
ContainerWeightCost, UnplacedItemCost, UsedContainerCost, UsedLengthCost, get_constraints,
)
cl.solve(problem, constraints=get_constraints()) # the defaults as-is
cl.solve(problem, constraints=[ # picked
UnplacedItemCost(), ContainerWeightCost(), UsedContainerCost(), UsedLengthCost(weight=0.001),
])
Only listed constraints are scored — leave one out and its term disappears from the score. To keep the defaults and change one, replace it by name::
picks = [UsedLengthCost(weight=0.001) if spec.name == "used_length_cost" else spec
for spec in get_constraints()]
(The module also carries ready-made default instances: unplaced_item_cost is
UnplacedItemCost(), and so on.)
Every spec takes five knobs:
weightlinear multiplier on the constraint cost.None= the component default (1, and 0 for the three opt-in costsUsedLengthCost,LoadBalanceCostandShippingCost);cl.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 container:weight * sign(c) * |c| ** exponent. 2.0 = squared, so concentrated violations grow much costlier.offset(keyword) shifts that shaping per container; 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 container below the offset — an empty one (cost 0) included — lowers the penalty. With an offset it is refused on hard, because hard 0 must mean no violation.
GroupSplitCost, IncompleteGroupCost and SingleContainerCost are the global
constraints: their knobs shape the single total, not a cost per container.
The same constraint may be picked several times; each pick is scored on its own with
its own knobs and the picks add up. cl.constraint_costs(problem, picks) keys a
second pick "<name>#2".
Names (name) are the C++ component names in snake_case
(UnplacedItemCost -> unplaced_item_cost). The core derives them
mechanically, so there is no hand-maintained alias table — check them with
cl.list_constraints(). Module-level instance names use the same snake_case,
so they match the strings list_constraints() prints.
With a selection the solve is single-start: run.parallel_solver_count is ignored. The
search is the same one, the domain's moves included.
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.
UnplacedItemCost
dataclass
¶
Bases: Constraint
Required items the decoder could not place. Default: hard, weight 1.
An item is unplaced when no free corner of its container takes it in an allowed
orientation: inside the walls, clear of the other items, with enough of its base
supported. It stays in the loading order and contributes its priority until
the search finds a placement. Optional items count in OptionalItemCost.
ContainerWeightCost
dataclass
¶
Bases: Constraint
Weight above a container's max_weight. Default: hard, weight 1.
Counts the whole loading order of the container, in the caller's weight unit. A
container without max_weight costs nothing.
StackingLoadCost
dataclass
¶
Bases: Constraint
Weight resting on an item above its max_load_on_top. Default: hard, weight 1.
Every item passes its own weight and what rests on it down to the items right under
it, shared by contact area. max_load_on_top=0 means nothing may stand on the item.
StackingRuleCost
dataclass
¶
Bases: Constraint
Items standing on each other against a stacking rule, and columns above an item's
max_stack_layers. Default: hard, weight 1.
An item stands on another when its base rests on the other's top. Each such pair whose
stack_groups a rule of the problem's stacking_rules forbids counts 1, and every layer
a column through an item has beyond its max_stack_layers counts 1.
UnloadingOrderCost
dataclass
¶
Bases: Constraint
Items in the way of one that leaves earlier. Default: hard, weight 1.
A lower unload_order leaves first (a route's stop number). An item blocks another
when it stands between it and the door, or above it. With the problem's
unloading_policy="reach", an item that lies wholly within reach_length of the other's
door-side face is not in its way; an item with manual_unload on top of the other is not
either. Items without unload_order are not counted.
StopZoneCost
dataclass
¶
Bases: Constraint
Items outside their stop's zone. Default: hard, weight 1.
With the problem's stop_zones, every container's length is cut into one zone per listed
stop, door side first: the first ends at the door, each next one where the one before it
starts, and the last reaches back to the closed end. An item whose unload_order has a
zone counts 1 when it reaches outside that zone along the length. No zones, no cost.
BalanceLimitCost
dataclass
¶
Bases: Constraint
A load's centre of gravity beyond the container's max_offset_length and
max_offset_width. Default: hard, weight 1.
Measured from the container's centre, along x as a share of half the length and along y as a share of half the width; what lies beyond a limit counts in whole percent, rounded up. A container without the limits costs nothing.
SegregationCost
dataclass
¶
Bases: Constraint
Items a segregation rule keeps apart that are not. Default: hard, weight 1.
Each pair of placed items in one container whose segregation_classes a rule of the
problem's segregation_rules keeps out of one container counts 1, and so does each pair
whose classes must keep a distance and stand closer than it in the floor plane.
AxleLoadCost
dataclass
¶
Bases: Constraint
Axle groups loaded above their max_load. Default: hard, weight 1.
For a container with two axle_groups, the load on each follows from the lever rule: a
placed item of weight w whose middle is at x puts w (rear - x) / (rear - front) on the
front group, the rest on the rear, plus each group's empty_load or share of
tare_weight. Checked at departure and after each stop's items are unloaded; the worst
stage counts, each group's excess rounded up to a whole weight unit and the two added.
UsedContainerCost
dataclass
¶
Bases: Constraint
Cost of the containers in use. Default: soft, weight 1.
A container is in use when it holds a placed item; it then costs its cost (1 by
default, so the total is the number of containers used).
OptionalItemCost
dataclass
¶
Bases: Constraint
Optional items left out. Default: soft, weight 1.
An item with optional=True is loaded where there is room; left out, it counts its
priority here (and nothing in UnplacedItemCost).
UsedLengthCost
dataclass
¶
Bases: Constraint
How far each load reaches from the closed end. Default: soft, weight 0 (opt-in).
The loading metres of a cargo space, in the caller's length unit. Give it a weight to pack towards the closed end.
LoadBalanceCost
dataclass
¶
Bases: Constraint
How far each load's centre of gravity is from the centre. Default: soft, weight 0 (opt-in).
Measured in the x-y plane, in thousandths of the container's half-diagonal: 0 is centred, 1000 a corner.
ShippingCost
dataclass
¶
Bases: Constraint
What the containers in use cost to ship. Default: soft, weight 0 (opt-in).
Per container holding a placed item, the price in the rate table of its zone of its
billed weight: the weight of its placed items plus its tare_weight, or its dimensional
weight (ceil(volume / dim_divisor)) when that is more. 0 without rate tables. It shares
the soft level with UsedContainerCost, so its weight is what one unit of money is worth
against one unit of container cost.
GroupSplitCost
dataclass
¶
Bases: Constraint
Groups spread over several containers. Default: soft, weight 1.
Items with the same group (the items of an order) belong in one container. A global
constraint: a single total, not a cost per container.
IncompleteGroupCost
dataclass
¶
Bases: Constraint
Groups loaded in part although their rule asks for all or none. Default: hard, weight 1.
For each group whose group_rules entry sets all_or_none, the smaller of its placed
items and the items left out: what it takes to load it whole or not at all. Use it on
groups of optional items: a group of required items is already all through
UnplacedItemCost, and taking one more of them out trades one cost for the other. A global
constraint: a single total.
SingleContainerCost
dataclass
¶
Bases: Constraint
Groups that must ship in one container spread over several. Default: hard, weight 1.
For each group whose group_rules entry sets single_container, the containers holding a
placed item of the group beyond the first. A global constraint: a single total.
get_constraints ¶
get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]
Return the cost function. Without arguments, all seventeen default constraints.
When constraints is given, that list is used as-is — only the listed
constraints are scored::
get_constraints([UnplacedItemCost(), UsedContainerCost(weight=10)])
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 cl.constraint_costs(problem) returns: per constraint, the
raw cost of each container (before weight, exponent, offset and level
rounding), or the single total of GroupSplitCost. Fetch it once and rescore
with different weights without re-solving::
raw = cl.constraint_costs(problem)
score(raw) # default set
score(raw, [UnplacedItemCost(), UsedContainerCost(weight=10)])
No solver and no search are involved. The arithmetic matches the engine —
each container 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.container_loading._core ¶
Type stubs for optimaru.container_loading._core — the container-loading C++ solver.
The problem object holds the solution: every container's items (item indices in
loading order) is the single sequence-shape decision variable. Where an item stands is
derived from that order by the placement decoder and written on the item
(container, sequence, x, y, z, placed_length, placed_width,
placed_height) by calculate_score and by every solve.
Coordinates: x runs along a container's length (0 = the closed end, the door is at
x = length), y along its width, z up. Lengths and weights are whole numbers in the
caller's unit.
Score (hard/soft, lexicographic), at the default weights: hard = -(items that found no place + weight above a container's max_weight + weight on an item above its max_load_on_top + stacking rules and layer limits broken + pairs where a later item blocks an earlier one + items outside their stop's zone + centre of gravity beyond its limits, in percent + pairs kept apart by a segregation rule that are not + axle loads above their limits at the worst stage + all-or-none groups loaded in part + one-container groups in several), soft = -(cost of the containers in use + optional items left out + containers a group is in beyond its first; used_length_cost, load_balance_cost and shipping_cost weigh 0 until a selection gives them a weight). An unplaced item counts its priority. The weights are the C++ components' defaults (constraint_info()); the problem carries none, except the weights the decoder weighs a place that would block or overload against leaving an item out: those of the last solve's constraints (the defaults on a problem never solved).
Rotation ¶
Bases: Enum
Which orientations the decoder may use for an item.
Item ¶
One box. The fields after manual_unload are derived: calculate_score and every solve write them.
length
instance-attribute
¶
length: int
Size along x as given, before any rotation (1 to 1,000,000).
max_load_on_top
instance-attribute
¶
max_load_on_top: int | None
Weight this item can carry; 0 = nothing on top. None = no limit.
unload_order
instance-attribute
¶
unload_order: int | None
Lower leaves first (a route's stop number). None = no order.
bottom_only
instance-attribute
¶
bottom_only: bool
Only on the floor (z = 0); other items may stand on it.
max_stack_layers
instance-attribute
¶
max_stack_layers: int | None
At most this many items in a column through it, itself included (>= 1). None = no limit.
stack_group
instance-attribute
¶
stack_group: str | None
The group the problem's stacking_rules name.
priority
instance-attribute
¶
priority: int
What leaving it out costs: an unplaced item counts its priority (1 to 1,000,000).
optional
instance-attribute
¶
optional: bool
Loaded where there is room: left out, it counts in optional_item_cost (soft), not in unplaced_item_cost, its weight does not count against max_weight, and the decoder leaves it out where it would put the placed weight above max_weight.
allowed_containers
instance-attribute
¶
allowed_containers: list[str]
The containers it may go in, by id or tag; [] = any. In another container's list it finds no place.
segregation_class
instance-attribute
¶
segregation_class: str | None
The class the problem's segregation_rules name.
manual_unload
instance-attribute
¶
manual_unload: bool
Lifted off by hand: on top of an item that leaves earlier, it is not counted in that item's way.
sequence
property
¶
sequence: int
0-based place among its container's placed items; -1 = not placed.
Container ¶
One physical space: a pallet, a rack bay, a cargo space, one carton. The fields
after items are derived: calculate_score and every solve write them.
length
instance-attribute
¶
length: int
Inner size along x: from the closed end to the door (1 to 1,000,000).
max_stack_height
instance-attribute
¶
max_stack_height: int | None
How high the load may reach (1 to 1,000,000; the decoder fills up to the lower of it and
height). None = up to height.
max_offset_length
instance-attribute
¶
max_offset_length: float | None
How far the placed load's centre of gravity may lie from the centre along x, as a share of half the length (0 to 1). None = no limit.
max_offset_width
instance-attribute
¶
max_offset_width: float | None
The same across, as a share of half the width. None = no limit.
tags
instance-attribute
¶
tags: list[str]
Names an item's allowed_containers may use besides the id.
tare_weight
instance-attribute
¶
tare_weight: int | None
The vehicle's empty weight, taken at the middle of the cargo space; not with empty loads (give both axle groups an empty_load, or neither).
axle_groups
instance-attribute
¶
axle_groups: list[tuple[str, int, int, int | None]]
(id, position, max_load, empty_load): two axle groups, front then rear, or none. position is along x from the closed end (negative = ahead of it).
dim_divisor
instance-attribute
¶
dim_divisor: int | None
Dimensional-weight divisor (1 to 2**62): in use, the container bills at least ceil(volume / dim_divisor) (shipping_cost). None = its weight alone.
zone
instance-attribute
¶
zone: str | None
Which rate table prices it (RateTable.zone); None = the table without a zone. A zone needs rate tables.
placed_items
property
¶
placed_items: list[int]
The items of the list that found a place, in loading order.
axle_loads
property
¶
axle_loads: list[tuple[int | None, list[float]]]
With axle groups: (after_stop, loads) at departure (None) and after each stop, one load per axle group; [] without them.
unloading_violations
property
¶
unloading_violations: list[tuple[int, int, str]]
The unloading pairs left, as unloading_order_cost counts them: (item, blocks, kind),
item indices; item (it leaves later) stands in the way of blocks, between it and
the door (kind "door") or on top of it ("top").
billed_weight
property
¶
billed_weight: int
With a placed item: max(loaded_weight + tare_weight, ceil(volume / dim_divisor)); 0 when it holds none.
shipping_cost
property
¶
shipping_cost: float
With rate tables and a placed item: the price of billed_weight in the rate table of its zone; else 0.
RateBreak ¶
One weight break of a rate table: a shipment billed at most max_weight costs price.
RateTable ¶
What one used container costs to ship, by its billed weight: the price of the first break whose max_weight is at least the billed weight. One table per zone; the table without a zone prices the containers without one.
breaks
instance-attribute
¶
breaks: list[RateBreak]
At least one, max_weight strictly ascending (0 to 2**62), prices finite and >= 0.
ContainerLoadingProblem ¶
Problem and solution in one object. NOTE: containers and items element access
returns copies; write loading orders with set_loading, or assign a whole list back.
ValueError for what the engine refuses: a min_support_ratio outside (0, 1], a repeated id, a size outside 1..1,000,000, a weight outside 0..1,000,000,000, a negative limit or cost, a max_stack_layers outside 1..1,000,000,000, a max_stack_height outside 1..1,000,000, an offset limit outside 0..1, a stacking rule with an empty group, a priority outside 1..1,000,000, a group rule for no item's group or a group ruled twice, allowed_containers naming no container's id or tag, a segregation rule without a class or with a distance outside 1..1,000,000, axle groups that are not two or stand at one place, a negative axle limit, empty load or tare, one empty load without the other or with a tare, a reach_length outside 0..1,000,000, a stop zone of a length outside 1..1,000,000 or two zones for one stop, a dim_divisor outside 1..2**62, a container zone without rate tables or without its table, a rate table without breaks, given twice for one zone, with breaks not strictly ascending or a negative price, a container whose billed weight can pass its table's top break (its dimensional weight, or the weight of the items allowed in it, at most its max_weight, plus its tare), an item listed twice, or items without a container.
min_support_ratio
instance-attribute
¶
min_support_ratio: float
Share of an item's base that must rest on the floor or on other items, in (0, 1].
stacking_rules
instance-attribute
¶
stacking_rules: list[tuple[str, str]]
(top, bottom): items whose stack_group is top may not stand on items whose stack_group is bottom. Anything not listed is allowed.
group_rules
instance-attribute
¶
group_rules: list[tuple[str, bool, bool]]
(group, all_or_none, single_container): load the items whose group is group all or
none, and in one container.
segregation_rules
instance-attribute
¶
segregation_rules: list[tuple[str, str, int | None]]
(a, b, distance): items of classes a and b in different containers (distance None), or
at least distance apart in the floor plane.
reach_length
instance-attribute
¶
reach_length: int
0 = strict; > 0 = an item that leaves later and lies wholly within this distance of an earlier item's door-side face is not in its way (unloading_order_cost).
stop_zones
instance-attribute
¶
stop_zones: list[tuple[int, int]]
(unload_order, length): one zone per stop along every container's length, door side first; the last reaches back to the closed end (stop_zone_cost). [] = none.
rate_tables
instance-attribute
¶
rate_tables: list[RateTable]
What a used container costs to ship by its billed weight, one table per zone (shipping_cost). [] = no shipping prices.
loading ¶
loading() -> list[list[int]]
The decision: per container, the item indices in loading order.
set_loading ¶
set_loading(loading: list[list[int]]) -> None
Bulk write of the decision: one list of item indices per container. ValueError for a wrong number of lists, an index out of range or an item listed twice.
containers_used ¶
containers_used() -> int
Containers that hold a placed item, as of the last calculate_score / solve.
unplaced_items ¶
unplaced_items() -> list[int]
Indices of the items that are not placed (in a list without a place, or in no list), as of the last calculate_score / solve.
SolverConfig ¶
The solver settings, by stage of the solve: construction, stop, perturbation, custom_moves, moves, 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.
Construction ¶
config.construction: How the first solution is built.
first_fit_decreasing
instance-attribute
¶
first_fit_decreasing: bool
True (default): the items no list holds go group by group and largest first (those that leave last before the others, the bottom_only ones before the rest, those with a max_load_on_top after them), each into the first container that takes it. False: the engine's cheapest insertion places them.
Stop ¶
config.stop: When the search stops: the first limit reached.
Perturbation ¶
CustomMoves ¶
config.custom_moves: A step's move, next: this use case's own moves, chosen adaptively on their share of steps.
empty_container
instance-attribute
¶
empty_container: bool
Enable EmptyContainerMove: it moves the items of one of the least filled containers into the others in a single step, the only way past the containers-used step function. An item moves only where the decoder still places it and everything placed before, within the weight limit, and without breaking a stacking limit, a stacking rule or the unloading order.
empty_container_candidates
instance-attribute
¶
empty_container_candidates: int
EmptyContainerMove empties one of this many least filled containers in use (3; 1 = always the least filled). ValueError below 1.
repack
instance-attribute
¶
repack: bool
Enable RepackPairMove: the items of two containers in use are loaded again (into those two and, every second time, an empty one as a third), dealt out group by group, a group whole wherever a container has room for it, and each container's share in the construction's loading order. It gathers a group two containers share and repacks loading orders that grew by moves; it is made only when every load comes out clean.
switch_container
instance-attribute
¶
switch_container: bool
Enable SwitchContainerMove: the load of one container goes into empty containers of another size or cost that cost no more, as it is into one or split over several. Used only when the containers differ; it is how a load reaches a cheaper carton.
stop_order
instance-attribute
¶
stop_order: bool
Enable StopOrderMove (registered only when at least two items set an unload_order, also for a single container): a container's loading order is put back in stop blocks, the latest stop first (items without an order keep their places), with one change inside one stop's block: an item moved or two swapped, or the block ordered afresh by volume, height, base area, depth or at random.
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.
nearby_probability
instance-attribute
¶
nearby_probability: float
Used only when at least half the items set an unload_order (a vehicle load): how often the move mix moves an item next to one of its nearby items, those of the same stop and the stops next to it (then the closest in volume), which keeps the stops in blocks; a ruin-and-recreate kick then tries only the places next to them (0.8). 0 disables nearby selection.
nearby_size
instance-attribute
¶
nearby_size: int
Size of the nearby neighbor list (20). Used, like nearby_probability, only when at least half the items set an unload_order.
Acceptance ¶
config.acceptance: Whether the candidate becomes the current solution.
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
0 = auto: clamp(4 * item 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.
parallel_solver_count
instance-attribute
¶
parallel_solver_count: int
Independent starts (threads), seed + i each; the best wins.
to_dict ¶
to_dict() -> dict[str, dict[str, object]]
Every setting by group and name: the shape of a request's solver_parameters.
Solver ¶
First-fit-decreasing construction by decode + Late Acceptance local search over
the loading orders (+ EmptyContainerMove, RepackPairMove, SwitchContainerMove,
StopOrderMove and adaptive ruin-and-recreate). Solves IN PLACE: sets every container's items, the derived
fields and problem.score. The lists the problem comes with are kept as the starting
point.
solve_with_constraints ¶
solve_with_constraints(problem: ContainerLoadingProblem, constraints: Iterable[Any] | None = ...) -> None
Score the same solve with a caller-chosen constraint set (see optimaru.container_loading.constraints). The given list replaces the default set; None keeps the default set. Single start. 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_score ¶
calculate_score(problem: ContainerLoadingProblem) -> Score
Decode every container, write where each item stands and recompute the score at the
default weights (also stores problem.score). It scores at the default weights but places
the items as the last solve did: the decode weighs a place that would block or overload
against leaving the item out by the weights of the last solve's constraints (the defaults
on a problem never solved). ValueError for a problem the engine refuses (see
ContainerLoadingProblem). An item in no container's list is reported by
unplaced_items() but costs nothing (solve lists every item before it scores).
update_placements ¶
update_placements(problem: ContainerLoadingProblem) -> None
Decode every container and write where each item stands (the derived fields of the
items and containers), leaving problem.score as it is. calculate_score does this and
scores at the default weights; a solve leaves both current.
generate_demo_data ¶
generate_demo_data(item_count: int = 40, container_count: int = 4, random_seed: int = 37) -> ContainerLoadingProblem
The demo: boxes of six kinds (mm and g; one kind fragile) for pallets of 1200 x 800 x 1500 mm that carry 600 kg each; the boxes go to three stores in turn (the groups "store-1" to "store-3"). Deterministic for a given random_seed.
list_constraints ¶
list_constraints() -> list[str]
Constraint names scored by this domain (default assembly order, snake_case): unplaced_item_cost, container_weight_cost, stacking_load_cost, stacking_rule_cost, unloading_order_cost, stop_zone_cost, balance_limit_cost, segregation_cost, axle_load_cost, used_container_cost, optional_item_cost, used_length_cost, load_balance_cost, shipping_cost, group_split_cost, incomplete_group_cost, single_container_cost. The same names optimaru.container_loading.constraints uses.
constraint_costs ¶
constraint_costs(problem: ContainerLoadingProblem, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]
Raw 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}}. The fourteen per-container
constraints list one cost per container, an empty one included (the scoped
stacking_rule_cost, balance_limit_cost, segregation_cost, axle_load_cost,
optional_item_cost and shipping_cost also name the containers they evaluate, units); the three globals (group_split_cost, incomplete_group_cost,
single_container_cost) list their one total. 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 "
constraint_info ¶
constraint_info() -> list[ConstraintInfo]
The constraint catalog, in list_constraints() order: unplaced_item_cost, container_weight_cost, stacking_load_cost, stacking_rule_cost, unloading_order_cost, stop_zone_cost, balance_limit_cost, segregation_cost and axle_load_cost (hard, 1), used_container_cost and optional_item_cost (soft, 1), used_length_cost, load_balance_cost and shipping_cost (soft, 0: opt-in, default_enabled False), group_split_cost (soft, 1, global), incomplete_group_cost and single_container_cost (hard, 1, global); all flippable, none a reward.