optimaru.box_sizing¶
Generated from the sources of optimaru/box_sizing/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.box_sizing ¶
Box sizing — Python wrapper of the C++ solver on the optimaru engine.
Which box sizes to stock: every parcel (the packed content of one shipment, by its bounding
size) ships in one of the candidate boxes, only a limited number of distinct boxes may be
in use, and the least air is shipped. One assignment-shape decision variable (Parcel.box,
a box index, -1 = unassigned) picks the box of each parcel; a parcel fits a box when its
three sides, sorted, are each at most the box's sorted sides (any rotation).
Score, at the default weights (1 each):
hard = -(length by which parcels exceed their box, over the sorted sides # parcel_fit_cost
+ parcel weight above the box's max_weight # box_weight_cost
+ distinct boxes in use above max_box_types) # box_type_limit_cost
soft = -(quantity x (box volume - parcel volume), over the parcels # void_volume_cost
+ quantity x the box's cost, over the parcels) # box_cost
Three soft costs are opt-in at weight 0: box_type_cost (the number of boxes in use: a
weight on it is the fixed cost of stocking one more size), board_area_cost (quantity x
the board of the box, 2 (lw + lh + wh)) and shipping_cost (quantity x the price of the
billed weight, max(weight, ceil(box volume / dim_divisor)), in the rate table of the
parcel's zone). The problem carries no weights: change one
through a constraint selection (see optimaru.box_sizing.constraints).
constraint_info() lists every constraint with its default level and weight.
Basic usage::
import optimaru.box_sizing as bs
problem = bs.generate_demo_data() # models.BoxSizingProblemModel
solved = bs.solve(problem, time_limit_seconds=2.0, random_seed=42)
print(solved.box_types_used, solved.void_volume, solved.fill_ratio)
print([(box.id, box.parcels) for box in solved.boxes if box.parcels])
solve also takes the compiled BoxSizingProblem and solves it in place. The JSON
contract is optimaru.box_sizing.models (pydantic).
optimaru.box_sizing.models ¶
Pydantic JSON contract for the box-sizing domain.
The canonical problem as JSON. The engine holds a parcel's box as a position in
boxes; the model names it by the box's id::
from optimaru.box_sizing.models import BoxSizingProblemModel
model = BoxSizingProblemModel.model_validate(data) # JSON -> pydantic
solved = bs.solve(model, time_limit_seconds=5.0) # a new model, with the outputs
print(solved.box_types_used, solved.void_volume, solved.fill_ratio)
Lengths and weights are whole numbers in the caller's unit (the guide's examples use mm
and g). The canonical problem carries no constraint weights (extra="forbid"): weights
come only from constraint selections, and the defaults are the C++ components'
(box_sizing.constraint_info()).
BoxModel ¶
Bases: StrictModel
One candidate box size.
ParcelModel ¶
Bases: StrictModel
The packed content of one shipment, by its bounding size. It fits a box when its three sides, sorted, are each at most the box's sorted sides (any rotation).
RateBreakModel ¶
Bases: StrictModel
One weight break of a rate table: a shipment billed at most max_weight costs price.
RateTableModel ¶
Bases: StrictModel
What one shipment costs to ship, by its billed weight: the price of the first break whose
max_weight is at least the billed weight.
BoxSizingProblemModel ¶
Bases: StrictModel
Which box sizes to stock: every parcel ships in one of the candidate boxes, at most
max_box_types distinct boxes are in use, and the least air is shipped.
to_core ¶
to_core() -> _core.BoxSizingProblem
pydantic -> engine object (the output fields are ignored; the engine recomputes them).
from_core
classmethod
¶
from_core(problem: BoxSizingProblem) -> BoxSizingProblemModel
engine object -> pydantic, including the boxes of the parcels, the score and the derived outputs.
BoxSizingRequest ¶
Bases: SolveRequest
The box sizing problem with the settings of one solve (see SolveRequest for those).
parameter_uses ¶
parameter_uses(problem: BoxSizingProblemModel) -> 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 the quantities are required, so never "set".
with_initial_solution ¶
with_initial_solution(problem, solution)
Return a copy of problem whose search starts from solution.
solution is a solved problem (what solve returned for a model), or a plain dict of
that shape (the JSON the API returned). Parcels are matched by id, and a parcel's box
is a box id, so the solution may list the boxes in another order. A parcel the solution
leaves out, or holds without a box, is placed around the others by the construction, and
only it, so a complete solution starts the search exactly from it. problem is not
mutated; the copy has warm_start set.
Raises ValueError naming the parcel for an unknown or repeated id and for a box that
is not one of the problem's candidate boxes.
solve_request ¶
solve_request(request: BoxSizingRequest, *, constraints=None) -> BoxSizingProblemModel
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.box_sizing.constraints ¶
Constraint assembly specs — an API for picking the cost function declaratively.
The default path (bs.solve(problem)) scores the five default constraints at their default
weights (the other three, board_area_cost, shipping_cost and box_type_cost, are opt-in:
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(problem, constraints=...).
A constraint list reads one way: one class call per constraint::
import optimaru.box_sizing as bs
from optimaru.box_sizing.constraints import BoxTypeCost, VoidVolumeCost, get_constraints
bs.solve(problem, constraints=get_constraints()) # the defaults as-is
bs.solve(problem, constraints=[ # one default changed
BoxTypeCost(weight=2_000_000) if spec.name == "box_type_cost" else spec
for spec in get_constraints()
])
Only listed constraints are scored — leave one out and its term disappears from the
score. (The module also carries ready-made default instances: void_volume_cost
is VoidVolumeCost(), and so on.)
Every spec takes five knobs:
weightlinear multiplier on the constraint cost.None= the component default (1, but 0 for BoardAreaCost, ShippingCost and BoxTypeCost: off until picked with a weight). The problem carries no weights;bs.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.exponentsign-preserving power shaping:weight * sign(c) * |c| ** exponent, per box for the six per-box constraints and on the one count for BoxTypeLimitCost and BoxTypeCost.offset(keyword) shifts that shaping; 0.0 = none.clip(keyword)True(the default) counts only what lies beyond the offset,max(0, c - offset) ** exponent;Falseshapesc - offsetas it is. With an offset it is refused on hard, 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. bs.constraint_costs(problem, picks) keys the
second pick "void_volume_cost#2".
Names (name) are the C++ component names in snake_case
(VoidVolumeCost -> void_volume_cost). The core derives them mechanically, so
there is no hand-maintained alias table — check them with bs.list_constraints().
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.
ParcelFitCost
dataclass
¶
BoxWeightCost
dataclass
¶
VoidVolumeCost
dataclass
¶
BoxCost
dataclass
¶
Bases: Constraint
What the boxes shipped cost. Default: soft, weight 1.
It shares the soft level with the void volume, so its weight says how much volume one unit of cost is worth.
BoardAreaCost
dataclass
¶
Bases: Constraint
The board the boxes shipped are made of. Default: soft, weight 0 (opt-in).
Pick it with a weight to prefer the boxes that use less board: its weight says how much volume one unit of area is worth, as it shares the soft level with the void volume.
ShippingCost
dataclass
¶
Bases: Constraint
What the parcels cost to ship by billed weight. Default: soft, weight 0 (opt-in).
A shipment bills its weight, or its box's dimensional weight (ceil(box volume /
dim_divisor)) when that is more, and pays the price of that weight in the rate table of
its zone. Its weight says how much volume one unit of money is worth; to minimise the
shipping cost alone, pick it with void_volume_cost and box_cost left out.
BoxTypeLimitCost
dataclass
¶
Bases: Constraint
At most max_box_types distinct boxes may be in use. Default: hard, weight 1.
A step function of "is this box used at all", which is why the solver has its own moves that close, open and swap a size.
BoxTypeCost
dataclass
¶
Bases: Constraint
The number of distinct boxes in use. Default: soft, weight 0 (opt-in).
Pick it with a weight to give every size a fixed cost: the weight is what stocking one more size costs, in the units of the soft level.
get_constraints ¶
get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]
Return the cost function. Without arguments, all eight constraints at their defaults
(board_area_cost, shipping_cost and box_type_cost at weight 0, so five of them score).
When constraints is given, that list is used as-is — only the listed
constraints are scored. To change just one default, list the others as they are::
[BoxCost(weight=1000) if spec.name == "box_cost" else spec for spec in get_constraints()]
Same contract as the C++ applyConstraints: an empty list (most likely a filter that came out empty) raises ValueError; 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 bs.constraint_costs(problem) returns: per constraint, the
raw cost of each box, or the one count of the two box-type constraints (before
weight, exponent, offset and level rounding). Fetch it once and rescore with
different weights without re-solving::
raw = bs.constraint_costs(problem)
score(raw) # default set
score(raw, [VoidVolumeCost(), BoxTypeCost(weight=2_000_000)])
No solver and no search are involved. The arithmetic matches the engine —
each box contributes weight * shape(cost, exponent, offset, clip) and
hard contributions are rounded per box before summing. 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.box_sizing._core ¶
Type stubs for optimaru.box_sizing._core — the box-sizing C++ solver.
The problem object holds the solution: each parcel's box (an index into
problem.boxes, -1 == unassigned) is the single assignment-shape decision variable.
Score (hard/soft, lexicographic), at the default weights (1 each): hard = -(length by which parcels exceed their box + parcel weight above the box's max_weight + distinct boxes in use above max_box_types), soft = -(quantity x (box volume - parcel volume) + quantity x box cost, over the parcels). Three soft costs are opt-in at weight 0: board_area_cost, shipping_cost (by billed weight, from the rate tables) and box_type_cost. The weights are the C++ components' defaults (constraint_info()); the problem carries none.
Box ¶
Problem fact: one candidate box size. Lengths and weights are whole numbers in the caller's unit.
max_weight
instance-attribute
¶
max_weight: int | None
The heaviest parcel the box carries; None == no limit.
required
instance-attribute
¶
required: bool
Already stocked and staying: it counts as in use even when no parcel takes it.
dim_divisor
instance-attribute
¶
dim_divisor: int | None
Dimensional-weight divisor (>= 1): a parcel in this box bills at least ceil(box volume / dim_divisor); None == it bills its own weight.
Parcel ¶
The packed content of one shipment, by its bounding size. It fits a box when its three sides, sorted, are each at most the box's sorted sides (any rotation).
quantity
instance-attribute
¶
quantity: int
How many shipments had this size; they all ship in the same box.
box
instance-attribute
¶
box: int
The decision variable: index into problem.boxes; -1 == unassigned.
zone
instance-attribute
¶
zone: str | None
Which rate table prices it; None == the table without a zone.
RateBreak ¶
One weight break of a rate table: a shipment billed at most max_weight costs price.
RateTable ¶
What one shipment costs to ship by its billed weight: the price of the first break
whose max_weight is at least the billed weight. zone None prices the parcels without
one.
BoxSizingProblem ¶
Problem and solution in one object. NOTE: boxes / parcels element access returns
copies; use set_assignment for the parcels' boxes. Replacing either list is fine.
rate_tables
instance-attribute
¶
rate_tables: list[RateTable]
One per zone; empty == no shipping prices (shipping_cost is 0). Element access returns copies: replace the list.
max_box_types
instance-attribute
¶
max_box_types: int | None
How many distinct boxes may be in use, the required ones included; None == no limit.
warm_start
instance-attribute
¶
warm_start: bool
True = the next solve starts from the parcels' boxes (a seed); every solve clears it.
box_types_used ¶
box_types_used() -> int
Distinct boxes in use: those a parcel ships in and the required ones.
void_volume ¶
void_volume() -> int
Sum over the assigned parcels of quantity * (box volume - parcel volume); a parcel larger than its box counts 0.
fill_ratio ¶
fill_ratio() -> float
Shipped parcel volume / shipped box volume; 0.0 when nothing is assigned. A parcel larger than its box (which does not fit it) counts as the box's volume, so the ratio is at most 1 and void_volume() is the shipped box volume times (1 - fill_ratio()).
parcels_per_box ¶
parcels_per_box() -> list[int]
Per box, the shipments in it: the quantities of its parcels, summed.
board_area ¶
board_area() -> int
Sum over the assigned parcels of quantity * 2 (lw + lh + wh) of their box.
billed_weight_per_box ¶
billed_weight_per_box() -> list[int]
Per box, over its parcels, quantity * billed weight: the parcel's weight, or the box's dimensional weight (ceil(volume / dim_divisor)) when that is more.
shipping_cost_per_box ¶
shipping_cost_per_box() -> list[float]
Per box, over its parcels, quantity * the price of the billed weight in the rate table of the parcel's zone; a parcel whose zone has no table counts 0.
set_assignment ¶
set_assignment(assignment: list[int]) -> None
Bulk write of the decision variable (range-checked when scored or solved).
SolverConfig ¶
The solver settings, by stage of the solve: stop, perturbation, strategies, 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.
strategies
instance-attribute
¶
strategies: Strategies
A step's move, first: built-in strategies, each drawn by its own weight in a fixed order.
custom_moves
instance-attribute
¶
custom_moves: CustomMoves
A step's move, next: this use case's own moves, taking turns evenly with the move mix 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).
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.
time_limit_seconds
instance-attribute
¶
time_limit_seconds: float
Wall-clock budget (30 s). 0 = no search: the greedy construction (or the seed, completed) comes back.
target_score
instance-attribute
¶
target_score: tuple[int, float]
(hard, soft): stop early once bestScore >= this. (0, -inf) stops at the first feasible solution.
Perturbation ¶
config.perturbation: When a stalled search is kicked, and the kick: a large ruin & recreate taken whatever it scores.
enabled
instance-attribute
¶
enabled: bool
False by default here: a kick re-places the ruined parcels one at a time, and each goes back to the size it had.
Strategies ¶
config.strategies: A step's move, first: built-in strategies, each drawn by its own weight in a fixed order.
ruin_recreate_weight
instance-attribute
¶
ruin_recreate_weight: float
Destroy-and-repair as an ordinary acceptor-judged move (the engine's strategies.ruin_recreate_weight). 0 = off.
CustomMoves ¶
config.custom_moves: A step's move, next: this use case's own moves, the moves on the set of sizes, taking turns evenly with the move mix on their share of steps.
share
instance-attribute
¶
share: float
Gate on how often a step may draw one of the moves on the set of sizes (CloseBoxMove, OpenBoxMove, SwapBoxMove); 1 = unrestricted. Inside the gate the three and the move mix take turns evenly, so three steps in four are theirs.
close_box
instance-attribute
¶
close_box: bool
Enable CloseBoxMove: take one size out of use and send each of its parcels to the cheapest remaining size that takes it.
open_box
instance-attribute
¶
open_box: bool
Enable OpenBoxMove: put one more size into use and pull in every parcel it serves cheaper. No move at max_box_types.
swap_box
instance-attribute
¶
swap_box: bool
Enable SwapBoxMove: open a size and close another in one step, the size whose closing costs the least three times in four. At max_box_types the only way to another set of sizes.
Moves ¶
config.moves: A step's move, otherwise: the move mix, by relative weight (0 turns a move off).
Acceptance ¶
config.acceptance: Whether the candidate becomes the current solution.
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
0 = auto: clamp(8 * box count, 100, 800).
reheat
instance-attribute
¶
reheat: bool
Late acceptance refills its history with a score just below its best (0.5% to 8% of the soft score, in turn) after two histories without an improving step, so the search leaves a set of sizes no single move improves. False: plain late acceptance, which from the greedy construction is a descent and nothing more.
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 ¶
Greedy construction over the sizes + late acceptance that starts over just below its best, with CloseBoxMove, OpenBoxMove and SwapBoxMove (ruin & recreate kicks off by default). Solves IN PLACE: fills parcel.box and problem.score, clears warm_start. A plain solve ignores the boxes on the parcels; with warm_start it starts from them. ValueError for what calculate_score refuses, for a parcel that fits none of the candidate boxes (by size and weight) and for more required boxes than max_box_types.
solve_with_constraints ¶
solve_with_constraints(problem: BoxSizingProblem, constraints: Iterable[Any] | None = ...) -> None
Score the same solve with a caller-chosen constraint set (see optimaru.box_sizing.constraints). The given list replaces the default set; None keeps the default set. Single start. The construction and the moves price the sizes with the picked weights of void_volume_cost, box_cost, board_area_cost, shipping_cost and box_type_cost (the weights alone: a level, an exponent or an offset shapes the score a step is judged by, not which step is proposed). 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: BoxSizingProblem, constraints: Iterable[Any] | None = ...) -> Score
Full recompute of the score (also stores problem.score). None scores the default set; a list scores exactly those picks (see optimaru.box_sizing.constraints), a name picked several times once per pick. ValueError for no candidate box, a repeated or empty id, a side outside 1..2,000,000, a weight or max_weight outside 0..1e12, a quantity below 1, a cost that is negative or not finite, max_box_types below 1, a shipped volume a double cannot hold exactly (summed quantities x the largest box volume above 2^53), a box outside -1..box count - 1, a dim_divisor below 1, a rate table that repeats a zone, has no breaks, breaks out of order or a negative price, a parcel whose zone has no rate table (when it has a zone or there are tables), a parcel that a box takes at a billed weight above its table's top break, and, once weight is billed (a dim_divisor or rate tables), summed quantities x the heaviest billed weight above 2^53.
list_constraints ¶
list_constraints() -> list[str]
Constraint names scored by this domain (default assembly order, snake_case): parcel_fit_cost, box_weight_cost, void_volume_cost, box_cost, board_area_cost, shipping_cost, box_type_limit_cost, box_type_cost. The same names optimaru.box_sizing.constraints uses.
constraint_costs ¶
constraint_costs(problem: BoxSizingProblem, 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 six per-box constraints
list one cost per candidate box, a box no parcel ships in included;
box_type_limit_cost and box_type_cost (global) list their one number. 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: parcel_fit_cost (hard, 1), box_weight_cost (hard, 1), void_volume_cost (soft, 1), box_cost (soft, 1), board_area_cost (soft, 0: opt-in), shipping_cost (soft, 0: opt-in), box_type_limit_cost (hard, 1), box_type_cost (soft, 0: opt-in); the three opt-in ones default_enabled False; all flippable, none a reward.