Skip to content

optimaru.bin_packing

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

optimaru.bin_packing

Bin packing — Python wrapper of the C++ solver on the optimaru engine.

Uniform-capacity one-dimensional bin packing with optional item colours and conflict pairs: one assignment-shape decision variable (Item.bin, a 0-based bin index, -1 = unassigned) puts every item in one of n identical bins.

Score, at the default weights (1 each): hard = -(load above capacity, per bin # bin_capacity_cost + items beyond the first of their colour, per bin # color_conflict_cost + conflict pairs sharing a bin) # item_conflict_cost soft = -(bins in use) # used_bins_cost The problem carries no weights: change one through a constraint selection, e.g. solve(problem, constraints=[..., UsedBinsCost(weight=2)]) (see optimaru.bin_packing.constraints). constraint_info() lists every constraint with its default level and weight.

Basic usage::

import optimaru.bin_packing as bp

problem = bp.BinPackingProblem(10, [bp.Item("A", 8), bp.Item("B", 7), bp.Item("C", 3), bp.Item("D", 2)])
bp.solve(problem, time_limit_seconds=1.0, random_seed=42)
print(problem.score, problem.bins_used(), problem.bin_loads())

problem.items returns copies: write bins with problem.set_assignment([...]). The JSON contract is optimaru.bin_packing.models (pydantic).

optimaru.bin_packing.models

Pydantic JSON contract for the bin-packing domain.

The canonical problem as JSON, mirroring _core's Item / BinPackingProblem::

from optimaru.bin_packing.models import BinPackingProblemModel

model = BinPackingProblemModel.model_validate(data)        # JSON -> pydantic
problem = model.to_core()                                  # pydantic -> engine
bp.solve(problem, time_limit_seconds=5.0)
solved = BinPackingProblemModel.from_core(problem)         # engine -> pydantic (+ outputs)

The canonical problem carries no constraint weights (extra="forbid"): weights come only from constraint selections, and the defaults (1 each) are the C++ components' (bin_packing.constraint_info()).

BinPackingProblemModel

Bases: StrictModel

to_core

to_core() -> _core.BinPackingProblem

pydantic -> engine object (the output fields are ignored; the engine recomputes them).

from_core classmethod

from_core(problem: BinPackingProblem) -> BinPackingProblemModel

engine object -> pydantic, including the bins, the score and the derived outputs.

BinPackingRequest

Bases: SolveRequest

The bin packing problem with the settings of one solve (see SolveRequest for those).

parameter_uses

parameter_uses(problem: BinPackingProblemModel) -> 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. bin_capacity and the weights 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 model or a dict of the same shape; items are matched by id. An item the solution leaves out, or holds at -1, is placed around the seeded bins by the best-fit construction before the search starts. Bins run from 0 to one below the item count, which is every bin a solve can return.

solve_request

solve_request(request: BinPackingRequest, *, constraints=None) -> BinPackingProblemModel

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.bin_packing.constraints

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

The default path (bp.solve(problem)) 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(problem, constraints=...).

A constraint list reads one way: one class call per constraint::

import optimaru.bin_packing as bp
from optimaru.bin_packing.constraints import BinCapacityCost, UsedBinsCost, get_constraints

bp.solve(problem, constraints=get_constraints())              # the defaults as-is
bp.solve(problem, constraints=[                                # picked
    BinCapacityCost(), UsedBinsCost(weight=10),
])

Only listed constraints are scored — leave one out and its term disappears from the score. (The module also carries ready-made default instances: bin_capacity_cost is BinCapacityCost(), and so on.)

Every spec takes five knobs:

  • weight linear multiplier on the constraint cost. None = the component default (1 for every bin-packing constraint). The problem carries no weights; bp.constraint_info() reports the defaults.
  • level None = the default level, otherwise Level.HARD or Level.SOFT (or the names "hard" and "soft"). This use case has no medium level: level="medium" raises ValueError.
  • exponent sign-preserving power shaping: weight * sign(c) * |c| ** exponent. Applied per BIN for the three per-bin constraints, and on the bin count for UsedBinsCost.
  • offset (keyword) shifts that shaping, at the same granularity; 0.0 = none.
  • clip (keyword) True (the default) counts only what lies beyond the offset, max(0, c - offset) ** exponent; False shapes c - offset as it is, so a bin below the offset — an empty one (cost 0) included, every bin 0 .. item count - 1 — lowers the penalty, and a bin count below it does too. With an offset it is refused on hard (the three per-bin constraints by default), because hard 0 must mean no violation.

The same constraint may be picked several times; each pick is scored on its own with its own knobs (its level included) and the picks add up. Every bin costs 1, and every bin beyond the tenth 100 on top::

bp.solve(problem, constraints=[
    *get_constraints(),
    UsedBinsCost(weight=100, offset=10),
])

bp.constraint_costs(problem, picks) keys the second pick "used_bins_cost#2".

Names (name) are the C++ component names in snake_case (BinCapacityCost -> bin_capacity_cost). The core derives them mechanically, so there is no hand-maintained alias table — check them with bp.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.

BinCapacityCost dataclass

Bases: Constraint

Load above the bin capacity, per bin. Default: hard, weight 1.

ColorConflictCost dataclass

Bases: Constraint

Items sharing a bin with another item of the same colour. Default: hard, weight 1.

Per bin: every item beyond the first of its colour. The exponent shapes each bin's sum (red x3 + blue x2 in one bin is 3, so exponent 2 gives 9).

ItemConflictCost dataclass

Bases: Constraint

Conflict pairs placed in one bin. Default: hard, weight 1.

Per bin: the listed pairs with both items in it (a pair listed twice counts twice). The exponent shapes each bin's count.

UsedBinsCost dataclass

Bases: Constraint

Number of bins in use (the objective). Default: soft, weight 1.

One global value; the exponent shapes the count itself (count ** exponent).

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([BinCapacityCost(), ColorConflictCost(), ItemConflictCost(), UsedBinsCost(weight=10)])

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 bp.constraint_costs(problem) returns: per constraint, the raw cost of each bin (used_bins_cost: the one bin count), before weight, exponent, offset and level rounding. Fetch it once and rescore with different weights without re-solving::

raw = bp.constraint_costs(problem)
score(raw)                                    # default set
score(raw, [BinCapacityCost(), UsedBinsCost(weight=10)])
score(raw, [UsedBinsCost(), UsedBinsCost(weight=100, offset=10)])

No solver and no search are involved. The arithmetic matches the engine — each bin contributes weight * shape(cost, exponent, offset, clip) and hard contributions are rounded per bin before summing (the same order as the engine). 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.bin_packing._core

Type stubs for optimaru.bin_packing._core — the bin-packing C++ solver.

The problem object holds the solution: each item's bin (a 0-based bin index into the n identical bins, -1 == unassigned) is the single assignment-shape decision variable.

Score (hard/soft, lexicographic), at the default weights (1 each): hard = -(load above capacity + items beyond the first of their colour in a bin + conflict pairs sharing a bin), soft = -(bins in use). The weights are the C++ components' defaults (constraint_info()); the problem carries none.

Score

is_feasible

is_feasible() -> bool

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

Item

One item packed into exactly one bin.

bin instance-attribute

bin: int

The decision variable: a 0-based bin index (0..item count - 1); -1 == unassigned.

BinPackingProblem

Problem and solution in one object. NOTE: items element access returns copies; use set_assignment for bin writes. Replacing items or conflicts is fine.

warm_start instance-attribute

warm_start: bool

True = the next solve starts from the items' bins (a seed); every solve clears it.

bins_used

bins_used() -> int

Distinct bins holding at least one item.

bin_loads

bin_loads() -> list[int]

[] when nothing is assigned, else the load of every bin 0..max bin.

assignment

assignment() -> list[int]

The current bin per item (-1 == unassigned).

set_assignment

set_assignment(assignment: list[int]) -> None

Bulk write of the decision variable (range-checked when scored or solved).

SolverConfig

spent_limit_seconds instance-attribute

spent_limit_seconds: float

Wall-clock budget (30 s). 0 = no search: the construction / seed comes back.

parallel_solver_count instance-attribute

parallel_solver_count: int

Independent starts (threads), seed + i each; the best wins.

late_acceptance_size instance-attribute

late_acceptance_size: int

0 = auto: clamp(8 * item count, 400, 3200).

ruin_recreate_as_move_weight instance-attribute

ruin_recreate_as_move_weight: float

Destroy-and-repair as an ordinary acceptor-judged move (the engine's ruin_recreate.as_move_weight). 0 = off.

value_recommender_probability instance-attribute

value_recommender_probability: float

Probability that a change move draws the item's new bin as the bin of a random other item (a bin in use) instead of uniformly over all n bins.

descent_weight instance-attribute

descent_weight: float

Assignment-shape best-improvement descent strategy weight. 0 = off.

custom_move_probability instance-attribute

custom_move_probability: float

Gate on how often a step may draw one of the macro moves (EmptyBinMove, RepackMove, TradeMove); 1 = unrestricted.

empty_bin_moves instance-attribute

empty_bin_moves: bool

Enable the bin-emptying macro move: it moves every item of one light bin into the other bins in a single step, the only way past the bins-used step function. It checks the capacity only.

empty_bin_candidates instance-attribute

empty_bin_candidates: int

EmptyBinMove and RepackMove empty one of this many lightest bins (1 = always the lightest); TradeMove takes its first bin from them every second time.

repack_moves instance-attribute

repack_moves: bool

Enable RepackMove: empty one light bin together with 1 to repack_partner_bins other light bins and put their items back best fit decreasing, only where they add no capacity, colour or conflict violation. The move that closes bins on instances with colours or conflicts.

repack_partner_bins instance-attribute

repack_partner_bins: int

Most partner bins RepackMove empties with its source (2; 0 = the source alone). ValueError below 0.

trade_moves instance-attribute

trade_moves: bool

Enable TradeMove: trade up to two items of one bin for up to two of another so that the fuller of the two bins gets fuller, or, when no trade does that, so that both keep their loads with other items. The bins-used score does not change until a bin is empty; this move works towards that.

fill_tie_break instance-attribute

fill_tie_break: bool

A step that keeps the score is taken when it does not lower the sum of the squared bin loads, and otherwise one time in eight. False: every such step is taken, as plain late acceptance does. The score itself, the limits and on_new_best are the same either way.

best_score_limit instance-attribute

best_score_limit: tuple[int, float]

(hard, soft): stop early once bestScore >= this. (0, -inf) stops at the first feasible solution.

Solver

Best-fit-decreasing construction + Late Acceptance local search (+ the EmptyBinMove, RepackMove and adaptive ruin-and-recreate). Solves IN PLACE: fills item.bin and problem.score, clears warm_start.

solve_with_constraints

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

Score the same solve with a caller-chosen constraint set (see optimaru.bin_packing.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: BinPackingProblem, 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.bin_packing.constraints), a name picked several times once per pick. ValueError for a bin_capacity <= 0, a repeated id, a weight <= 0, a bad conflict or a bin outside -1..item count - 1.

list_constraints

list_constraints() -> list[str]

Constraint names scored by this domain (default assembly order, snake_case): bin_capacity_cost, color_conflict_cost, item_conflict_cost, used_bins_cost. The same names optimaru.bin_packing.constraints uses.

constraint_costs

constraint_costs(problem: BinPackingProblem, 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 three per-bin constraints list one cost per bin 0..item count - 1, an empty bin included; used_bins_cost (global) lists the one bin count. 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 "#" from the second on. optimaru.bin_packing.constraints.score() turns it into a score. Raises ValueError for the same facts as calculate_score.

constraint_info

constraint_info() -> list[ConstraintInfo]

The constraint catalog, in list_constraints() order: bin_capacity_cost (hard, 1), color_conflict_cost (hard, 1), item_conflict_cost (hard, 1), used_bins_cost (soft, 1); all flippable, none a reward, all scored by default (default_enabled).