optimaru.assembly_line_balancing¶
Generated from the sources of optimaru/assembly_line_balancing/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.assembly_line_balancing ¶
Assembly-line balancing — Python wrapper of the C++ solver on the optimaru engine.
Simple assembly-line balancing (SALBP-1) with zoning and station domains: one
assignment-shape decision variable (Task.station, a station index, -1 = unassigned)
puts every task on one station of the line.
Score, at the default weights: hard = -(capacity overflow + reversed precedences + stations beyond max_stations + station-domain distance + missed fixed stations + forbidden stations hit + extra stations of same-station groups + different-station pairs together) soft = -(stations used) # workload_imbalance_cost is opt-in (weight 0) The problem carries no weights: change one through a constraint selection, e.g.::
picks = [
WorkloadImbalanceCost(weight=1) if spec.name == "workload_imbalance_cost" else spec
for spec in get_constraints()
]
solve(problem, constraints=picks)
See optimaru.assembly_line_balancing.constraints; constraint_info() lists every constraint with its
default level and weight.
Basic usage::
import optimaru.assembly_line_balancing as alb
from optimaru.assembly_line_balancing.models import AssemblyLineBalancingProblemModel
problem = AssemblyLineBalancingProblemModel.model_validate(data)
solved = alb.solve(problem, time_limit_seconds=5.0, random_seed=42) # the model: a new, solved model
core = problem.to_core(); alb.solve(core) # or the engine object, in place
solve, calculate_score and constraint_costs take the pydantic model or the engine
object (AssemblyLineBalancingProblem, models.AssemblyLineBalancingProblemModel.to_core()).
optimaru.assembly_line_balancing.models ¶
The canonical assembly-line-balancing problem (pydantic v2) and its engine conversion.
AssemblyLineBalancingProblemModel is the JSON contract (tasks by id); to_core()
builds the C++ _core.AssemblyLineBalancingProblem (tasks by index) and
from_core() builds the model back, stations and results included::
from optimaru.assembly_line_balancing.models import AssemblyLineBalancingProblemModel
core = AssemblyLineBalancingProblemModel.model_validate(data).to_core()
alb.solve(core, time_limit_seconds=5) # in place
result = AssemblyLineBalancingProblemModel.from_core(core)
The canonical problem carries no constraint weights: weights come only from
constraint selections, and the defaults are the C++ components'
(assembly_line_balancing.constraint_info()).
AssemblyLineBalancingProblemModel ¶
Bases: StrictModel
to_core ¶
to_core() -> _core.AssemblyLineBalancingProblem
pydantic -> engine object: ids become task indices, None stays "no limit".
The stations and warm_start are copied; the result fields are ignored (the
engine recomputes them).
from_core
classmethod
¶
from_core(problem: AssemblyLineBalancingProblem) -> AssemblyLineBalancingProblemModel
engine object -> pydantic: the facts, the stations, warm_start and the results
(station_loads, stations_used from the stations; the score last computed on the core,
0hard/0soft if it was never scored).
AssemblyLineBalancingRequest ¶
Bases: SolveRequest
The assembly line balancing problem with the settings of one solve (see SolveRequest for those).
parameter_uses ¶
parameter_uses(problem: AssemblyLineBalancingProblemModel) -> 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. cycle_time and the durations 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; tasks are matched by id. A task the solution
leaves out, or holds at -1, is placed by the normal construction. Anything solve returns is accepted, feasible
or not: max_stations, station domains and fixed_station stay hard penalties, so a seed may break them, and
solve itself can return indices at or above the task count or max_stations.
solve_request ¶
solve_request(request: AssemblyLineBalancingRequest, *, constraints=None) -> AssemblyLineBalancingProblemModel
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.assembly_line_balancing.constraints ¶
Constraint assembly specs — an API for picking the cost function declaratively.
The default path (alb.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::
import optimaru.assembly_line_balancing as alb
from optimaru.assembly_line_balancing.constraints import (
StationCapacityCost, UsedStationsCost, WorkloadImbalanceCost, get_constraints,
)
solved = alb.solve(problem, constraints=get_constraints()) # the defaults as-is
picks = [
WorkloadImbalanceCost(weight=1) if spec.name == "workload_imbalance_cost" else spec
for spec in get_constraints()
]
solved = alb.solve(problem, constraints=picks) # one default changed
solved = alb.solve(problem, constraints=[StationCapacityCost(), UsedStationsCost()]) # picked
Only listed constraints are scored — leave one out and its term disappears from
the score. (The module also carries ready-made default instances:
station_capacity_cost is StationCapacityCost(), and so on.)
Every spec takes five knobs:
weightlinear multiplier on the constraint cost.None= the component default (1 for every constraint except the opt-in WorkloadImbalanceCost, 0). The problem carries no weights;alb.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:weight * sign(c) * |c| ** exponent, per station for the per-station constraints and on the single total for the global ones (TaskPrecedenceCost, SameStationGroupsCost, UsedStationsCost, WorkloadImbalanceCost).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;Falseshapesc - offsetas it is, so a station below the offset — an empty one (cost 0) included — lowers the penalty, and a global total below it does too. MaxStationsCost and ForbiddenTaskStationsCost evaluate only their own stations (frommax_stationson, and the stations some task forbids;constraint_costs()lists them as"units"), soclip=Falsecharges those and no other. With an offset it is refused on hard (every constraint but UsedStationsCost and WorkloadImbalanceCost 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 used station costs 1, and each one beyond the fourth 10 on top::
solved = alb.solve(problem, constraints=[
*get_constraints(),
UsedStationsCost(weight=10, offset=4),
])
alb.constraint_costs(problem, picks) keys the second pick "used_stations_cost#2".
Names (name) are the C++ component names in snake_case
(StationCapacityCost -> station_capacity_cost). The core derives them
mechanically, so there is no hand-maintained alias table — check them with
alb.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.
StationCapacityCost
dataclass
¶
TaskPrecedenceCost
dataclass
¶
MaxStationsCost
dataclass
¶
TaskStationBoundsCost
dataclass
¶
FixedTaskStationsCost
dataclass
¶
ForbiddenTaskStationsCost
dataclass
¶
SameStationGroupsCost
dataclass
¶
DifferentStationPairsCost
dataclass
¶
UsedStationsCost
dataclass
¶
Bases: Constraint
The number of stations in use (the SALBP-1 objective). Default: soft, weight 1.
A step function of "is this station used", so moving one task cannot cross it — that is why the domain carries a separate CloseStationMove.
WorkloadImbalanceCost
dataclass
¶
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::
picks = [
WorkloadImbalanceCost(weight=1) if spec.name == "workload_imbalance_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 alb.constraint_costs(problem) returns: per constraint, the
raw cost of each station (one total for the global constraints), before
weight, exponent, offset and level rounding. Fetch it once and rescore with
different weights without re-solving::
raw = alb.constraint_costs(problem)
score(raw) # default set
score(raw, [StationCapacityCost(), WorkloadImbalanceCost(weight=1)])
score(raw, [UsedStationsCost(), UsedStationsCost(weight=10, offset=4)])
No solver and no search are involved. The arithmetic matches the engine —
each evaluated unit contributes weight * shape(cost, exponent, offset, clip)
and hard contributions are rounded per unit 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 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.assembly_line_balancing._core ¶
Type stubs for optimaru.assembly_line_balancing._core — the assembly-line-balancing
C++ solver.
The problem object holds the solution: each task's station (a station index,
-1 == unassigned) is the single assignment-shape decision variable. Stations are not
bounded above by the facts; a solve freezes the value range at
max(task count, 1 + max station) after its construction (station_count).
Score (hard/soft, lexicographic), at the default weights: hard = -(the eight hard raw costs, weight 1 each), soft = -(stations used); the workload range is an opt-in objective (default weight 0). The weights are the C++ components' defaults (constraint_info()); the problem carries none.
Task ¶
One task with its processing time and station domain.
Precedence ¶
before (a task index) must not sit on a later station than after.
TaskGroup ¶
Tasks (indices) that should share one station.
TaskPair ¶
Two tasks (indices) that must not share a station.
AssemblyLineBalancingProblem ¶
Problem and solution in one object. NOTE: tasks element access returns copies; use
set_assignment for bulk station writes.
warm_start
instance-attribute
¶
warm_start: bool
Start the next solve from the current stations (tasks at -1 go through the construction). False: the solve ignores the input stations. Reset to False by every solve.
station_count
property
¶
station_count: int
The value range of the last solve / scoring: max(task count, 1 + max station).
station_loads ¶
station_loads() -> list[int]
Processing time per station 0..max(station), empty middle stations included.
set_assignment ¶
set_assignment(assignment: list[int]) -> None
Bulk write of the decision variable (every station >= -1).
SolverConfig ¶
spent_limit_seconds
instance-attribute
¶
spent_limit_seconds: float
Wall-clock budget (30 s). 0 stops before the first step: the solve returns the construction, or a complete warm-start seed, unchanged.
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
0 = auto: clamp(8 * task 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); one such move costs ~ruinCount * station count score evaluations. 0 = off.
value_recommender_probability
instance-attribute
¶
value_recommender_probability: float
Probability that a change move draws the task's new station from its current precedence / domain window instead of uniformly over all stations (0.5).
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 CloseStationMove; 1 = unrestricted.
close_station_moves
instance-attribute
¶
close_station_moves: bool
Enable the station-closing macro move: it empties one used station in a single step, the only way past the stations-used step function.
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 ¶
Domain construction + Late Acceptance local search (+ adaptive ruin-and-recreate, CloseStationMove). Solves IN PLACE: fills task.station and problem.score and resets warm_start to False.
solve_with_constraints ¶
solve_with_constraints(problem: AssemblyLineBalancingProblem, constraints: Iterable[Any] | None = ...) -> None
Score the same solve with a caller-chosen constraint set (see optimaru.assembly_line_balancing.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: AssemblyLineBalancingProblem) -> Score
Full recompute of the score at the default constraints (also stores problem.score). Unassigned tasks contribute nothing.
list_constraints ¶
list_constraints() -> list[str]
Constraint names scored by this domain (catalog order, snake_case): station_capacity_cost, task_precedence_cost, max_stations_cost, task_station_bounds_cost, fixed_task_stations_cost, forbidden_task_stations_cost, same_station_groups_cost, different_station_pairs_cost, used_stations_cost, workload_imbalance_cost. The same names optimaru.assembly_line_balancing.constraints uses.
constraint_costs ¶
constraint_costs(problem: AssemblyLineBalancingProblem, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]
Raw cost of every constraint, before weight/exponent/offset/level, in
list_constraints() order: {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}}. "costs" has
one entry per station (0 .. station_count - 1) for a per-station constraint and one total
for a global one (task_precedence_cost, same_station_groups_cost, used_stations_cost,
workload_imbalance_cost); the scoped max_stations_cost and forbidden_task_stations_cost
add "units", the stations they evaluate (ascending). 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: the eight hard constraints (hard, 1), used_stations_cost (soft, 1) and workload_imbalance_cost (soft, 0, default_enabled False); all flippable, none a reward.