Skip to content

optimaru.knapsack

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

optimaru.knapsack

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

The 0/1 knapsack with multidimensional resource capacities, mandatory and forbidden items, selection-group bounds and item dependencies: one assignment-shape decision variable (Item.selected, 1 = selected, 0 = not) per item.

Score, at the default weights: hard = -(weight over capacity + resource overflow + unselected mandatory items + selected forbidden items + selection-group shortfall/excess + unmet item dependencies) soft = +(selected value) # selected_value_cost is a reward The problem carries no weights: change one through a constraint selection, e.g.::

picks = [SelectedValueCost(weight=2) if spec.name == "selected_value_cost" else spec for spec in get_constraints()]
solve(problem, constraints=picks)

See optimaru.knapsack.constraints; constraint_info() lists every constraint with its default level and weight.

Basic usage::

from optimaru import knapsack
from optimaru.knapsack.models import KnapsackProblemModel

problem = KnapsackProblemModel.model_validate(data)
solved = knapsack.solve(problem, time_limit_seconds=5.0, random_seed=42)   # the model: a new, solved model
core = problem.to_core(); knapsack.solve(core)                     # or the engine object, in place

solve, calculate_score and constraint_costs take the pydantic model or the engine object (KnapsackProblem, models.KnapsackProblemModel.to_core()).

optimaru.knapsack.models

Pydantic models of the knapsack problem — the canonical JSON contract.

KnapsackProblemModel is the JSON contract (items by id); to_core() builds the engine object (optimaru.knapsack._core.KnapsackProblem, items by index) and from_core() builds the model back, selection and results included::

core = KnapsackProblemModel.model_validate(data).to_core()
knapsack.solve(core, time_limit_seconds=5)
result = KnapsackProblemModel.from_core(core)

knapsack.solve(model) does the same round trip on a copy: it returns a new, solved model and leaves the one passed in as it was.

KnapsackProblemModel

Bases: StrictModel

to_core

to_core() -> _core.KnapsackProblem

pydantic -> engine object: ids become item indices.

resource_capacities becomes the resource list in dict order (the order of nothing but the declaration), requires the item's required_items, repeated mandatory / forbidden / required entries stay repeated, a group's max_selected=None stays None (the group size). selected becomes 1 / 0 and warm_start is copied; the result fields are ignored (the engine recomputes them).

from_core classmethod

from_core(problem: KnapsackProblem) -> KnapsackProblemModel

engine object -> pydantic: the facts, the selection (an undecided item, -1, is not selected), warm_start and the results (total_weight, total_value from the selection; the score last computed on the core, 0hard/0soft if it was never scored).

An item's resource_usage comes back with its keys sorted: the engine keeps it in a map, so only the order differs from the model to_core() was built from (the dicts compare equal). resource_capacities keeps its declaration order. knapsack.solve(model) fills only the selection and the results into a copy of the model, so its result keeps the model's own order.

KnapsackRequest

Bases: SolveRequest

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

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 explicit False means not selected and stays that way. selected cannot express "undecided", so an item the solution leaves out is run through the greedy selection here (optimaru.knapsack._core.greedy_selection: value density order, weight capacity only), around the seeded load, and solve then fills in nothing.

solve_request

solve_request(request: KnapsackRequest, *, constraints=None) -> KnapsackProblemModel

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.

parameter_uses

parameter_uses(problem: KnapsackProblemModel) -> list[ParameterUse]

The parameters problem sets away from their defaults that act only through a cost.

knapsack.solve (and so solve_request) refuses a selection that holds none of a parameter's costs (optimaru._constraint.require_costs). The table is in the use-case guide ("Parameters and their costs", docs/use-cases/README.md).

optimaru.knapsack.constraints

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

The default path (knapsack.solve(problem)) scores every default constraint at its default weight. 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::

from optimaru import knapsack
from optimaru.knapsack.constraints import (
    KnapsackCapacityCost, MandatoryItemsCost, SelectedValueCost, get_constraints,
)

solved = knapsack.solve(problem, constraints=get_constraints())  # defaults as-is
picks = [
    SelectedValueCost(weight=2) if spec.name == "selected_value_cost" else spec
    for spec in get_constraints()
]
solved = knapsack.solve(problem, constraints=picks)                     # one default changed
solved = knapsack.solve(problem, constraints=[  # picked
    KnapsackCapacityCost(), MandatoryItemsCost(), SelectedValueCost(),
])

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

Every spec takes five knobs:

  • weight linear multiplier on the constraint cost. None = the component default (1 for every knapsack constraint). The problem carries no weights; knapsack.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. SelectedValueCost is a reward and always soft: level="hard" raises ValueError.
  • exponent sign-preserving power shaping: weight * sign(c) * |c| ** exponent on each constraint's single total (every knapsack constraint is global), e.g. the summed resource overflow.
  • offset (keyword) shifts that shaping of the total; 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 total below the offset — a raw 0 included — lowers the penalty. With an offset it is refused on hard (the six penalties by default), because hard 0 must mean no violation. On the SelectedValueCost reward (raw -value) a threshold offset rewards only the value beyond it, a literal one adds offset to the reward.

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. The resource overflow plus its square beyond 10 units::

solved = knapsack.solve(problem, constraints=[
    KnapsackCapacityCost(),
    ResourceCapacityCost(),
    ResourceCapacityCost(exponent=2, offset=10),
    SelectedValueCost(),
])

knapsack.constraint_costs(problem, picks) keys the second pick "resource_capacity_cost#2".

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

KnapsackCapacityCost dataclass

Bases: Constraint

Selected weight above the knapsack capacity. Default: hard, weight 1.

ResourceCapacityCost dataclass

Bases: Constraint

Selected usage above each declared resource capacity. Default: hard, weight 1.

MandatoryItemsCost dataclass

Bases: Constraint

Mandatory items left out. Default: hard, weight 1.

ForbiddenItemsCost dataclass

Bases: Constraint

Forbidden items selected. Default: hard, weight 1.

SelectionGroupBoundsCost dataclass

Bases: Constraint

Selection groups below their minimum or above their maximum. Default: hard, weight 1.

ItemDependencyCost dataclass

Bases: Constraint

Selected items whose required item is left out. Default: hard, weight 1.

SelectedValueCost dataclass

Bases: Constraint

Total value of the selection, a reward (raw cost <= 0). Default: soft, weight 1; never hard.

get_constraints

get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]

Return the cost function. Without arguments, every default constraint.

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::

picks = [
    SelectedValueCost(weight=2) if spec.name == "selected_value_cost" else spec
    for spec in get_constraints()
]
get_constraints(picks)

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 knapsack.constraint_costs(problem) returns: per constraint its raw total (a one-element list), before weight, exponent, offset and level rounding. Fetch it once and rescore with different weights without re-solving::

raw = knapsack.constraint_costs(problem)
score(raw)                                              # default set
score(raw, [KnapsackCapacityCost(), SelectedValueCost(weight=2)])
score(raw, [MandatoryItemsCost(), MandatoryItemsCost(exponent=2, offset=1)])

No solver and no search are involved. The arithmetic matches the engine — each constraint contributes weight * shape(cost, exponent, offset, clip) and hard contributions are rounded per constraint before summing (the same order as the engine; rounding the total afterwards gives different values for fractional hard weights). A second pick of a constraint reads the same raw total with its own knobs.

When constraints is given, only those constraints are scored — the same semantics as get_constraints. Unknown names raise ValueError; so do level="medium" (no medium level here) and level="hard" on the selected_value_cost reward.

optimaru.knapsack._core

Type stubs for optimaru.knapsack._core — the knapsack C++ solver.

The problem object holds the solution: each item's selected (1 = selected, 0 = not, -1 = undecided, counted as not selected) is the single assignment-shape decision variable.

Score (hard/soft, lexicographic), at the default weights: hard = -(weight over capacity + resource overflow + unselected mandatory entries + selected forbidden entries + selection-group shortfall/excess + unmet item dependencies), soft = +(selected value), a reward. 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.

Resource

Problem fact: one additional capacity dimension (a resource_capacities entry).

Item

One candidate item.

resource_usage instance-attribute

resource_usage: dict[str, int]

Usage per resource id; ids without a declared Resource are ignored.

required_items instance-attribute

required_items: list[int]

Indices of the items that must be selected with this one (the model's requires); repeats count separately, a self-dependency never counts.

selected instance-attribute

selected: int

The decision variable: 1 = selected, 0 = not selected, -1 = undecided.

SelectionGroup

Problem fact: between min_selected and max_selected of items must be selected.

max_selected instance-attribute

max_selected: int | None

None = the group size.

KnapsackProblem

Problem and solution in one object. NOTE: items (and the other lists) element access returns copies; use set_assignment for bulk selection writes.

resources instance-attribute

resources: list[Resource]

In declaration order (the order of the model's resource_capacities).

warm_start instance-attribute

warm_start: bool

Start the next solve from the current selection (undecided items go through the greedy construction); the solve resets it to False.

total_weight

total_weight() -> int

Weight of the selected items.

total_value

total_value() -> int

Value of the selected items.

assignment

assignment() -> list[int]

The decision variable per item (1 / 0 / -1).

set_assignment

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

Bulk write of the decision variable (each value -1, 0 or 1).

SolverConfig

spent_limit_seconds instance-attribute

spent_limit_seconds: float

Wall-clock budget (30 s by default). 0 returns the construction (or a warm-start seed) unchanged.

step_count_limit instance-attribute

step_count_limit: int

0 = no step limit.

parallel_solver_count instance-attribute

parallel_solver_count: int

Independent starts (seed + i each); the best wins. Ignored by solve_with_constraints.

late_acceptance_size instance-attribute

late_acceptance_size: int

0 = auto: clamp(8 * item count, 400, 3200). The first stage's length: the search restarts with a doubled history when it stalls and the next stage fits in the budget. A solve that starts from a given solution keeps this one length.

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.05 by default, 0 = off.

change_move_weight instance-attribute

change_move_weight: float

A change move flips one item.

swap_move_weight instance-attribute

swap_move_weight: float

A swap move trades a selected item for an unselected one.

descent_weight instance-attribute

descent_weight: float

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

nearby_probability instance-attribute

nearby_probability: float

Bias swap partners toward items of similar weight with this probability. 0 = off (uniform-random).

core_repack_moves instance-attribute

core_repack_moves: bool

Re-decide a window of the value / weight order around the break item exactly, by dynamic programming over the weight (on by default): the exchanges at the capacity boundary that no single flip or swap reaches. It looks at the capacity only; the score judges everything else.

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

Greedy construction + Late Acceptance local search with the core repack move (+ adaptive ruin-and-recreate). Solves IN PLACE: sets item.selected, problem.score and warm_start = False.

solve_with_constraints

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

Score the same solve with a caller-chosen constraint set (see optimaru.knapsack.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 (its level included), and the instances add up. There is no medium level: level="medium" raises ValueError.

ConstraintInfo

Bases: NamedTuple

One constraint-catalog row, read off the C++ default assembly.

calculate_score

calculate_score(problem: KnapsackProblem) -> Score

Full recompute of the score at the default constraints (also stores problem.score). Raises ValueError on invalid facts.

greedy_selection

greedy_selection(problem: KnapsackProblem, fixed: list[int]) -> list[bool]

The greedy construction: items by descending value / weight (ties in item order) while the weight fits the capacity. fixed holds one entry per item: 0 / 1 kept as given (the load starts at the items fixed to 1), -1 decided by the greedy.

list_constraints

list_constraints() -> list[str]

Constraint names scored by this domain (default assembly order, snake_case): knapsack_capacity_cost, resource_capacity_cost, mandatory_items_cost, forbidden_items_cost, selection_group_bounds_cost, item_dependency_cost, selected_value_cost. The same names optimaru.knapsack.constraints uses.

constraint_costs

constraint_costs(problem: KnapsackProblem, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]

Raw cost of every constraint, before weight/exponent/offset/level: {key: {"costs": [total], "weight": float, "exponent": float, "offset": float, "clip": bool, "global": bool, "level": "hard" | "soft", "reward": bool, "level_flippable": bool, "name": str, "label": str, "default_weight": float, "default_level": str}}, "level" being the level in effect (the pick's, or the default) and "hard" the same as level == "hard". Every knapsack constraint is global, so "costs" holds one raw 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 "#" from the second on. optimaru.knapsack.constraints.score() turns it into a score.

constraint_info

constraint_info() -> list[ConstraintInfo]

The constraint catalog, in list_constraints() order: the six hard constraints at weight 1 (flippable), then selected_value_cost (soft, weight 1, a reward: level="hard" is refused and its level cannot change); all scored by default (default_enabled).