optimaru.food_packaging¶
Generated from the sources of optimaru/food_packaging/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.food_packaging ¶
Food packaging — Python wrapper of the C++ solver on the optimaru engine.
Assigns packaging jobs (Job) to production lines (Line) in order. The decision is Line.jobs, an ordered list of jobs per line (the engine's sequence shape); jobs in no line's list are unassigned, an extra unassigned pool list exposed to the engine. Each job's times are derived from list positions::
startCleaning(first job) = line.start # zero-length cleaning window
startCleaning(otherwise) = end of the previous job
startProduction = startCleaning + cleanup(previous product -> product)
end = startProduction + duration
The second decision, each line's operator (Line.operator_index), is optimized by alternation: the solver wrapper reassigns it by hill climbing between engine legs (the engine supports one variable model per solution). With operators >= lines the assignment is injective and the conflict constraint is always 0, so it is exactly equivalent to one engine run.
Times are exchanged as "minutes" (int64) from a shared origin (the demo instance has
Monday 00:00 == minute 0; the pydantic mirror optimaru.food_packaging.models converts between
epoch minutes and datetime.datetime).
Constraints (three score levels, hard / medium / soft; the mapping onto engine Score is the domain's medium fold engine.soft = medium * 10^10 + soft, and the order is preserved exactly while |soft| < 10^10 and |medium| < 9*10^5): hard 1. max_end_time_cost -1 per minute past max_end_time hard 2. operator_cleaning_conflict_cost for job pairs on lines of the same operator whose cleaning windows [startCleaning, startProduction) overlap, -overlapping minutes medium 3. after_ideal_end_time_cost -1 per minute past ideal_end_time medium 4. unassigned_jobs_cost -duration minutes per unassigned job soft 5. squared_makespan_cost -(end - line start)^2 per last job of a line (min_start_minute and priority are data fields no constraint reads.)
The constraints and their defaults (level, weight in units of that level) live in the C++
components; constraint_info() reports them, list_constraints() lists the names and
constraint_costs() gives the raw per-constraint costs of a schedule (the only
per-constraint surface)::
{row.name: (row.default_level, row.default_weight) for row in fp.constraint_info()}
# {'max_end_time_cost': ('hard', 1.0), ..., 'unassigned_jobs_cost': ('medium', 1.0)}
Usage::
import optimaru.food_packaging as fp
schedule = fp.generate_demo_data()
fp.solve(schedule, time_limit_seconds=10.0, random_seed=42)
print(schedule.score, schedule.score.is_feasible())
optimaru.food_packaging.models ¶
Pydantic v2 mirror of the engine domain — for JSON serialization/deserialization.
Mirrors _core's Product/Operator/Line/Job/PackagingSchedule 1:1, but times are
datetime.datetime (naive, converted to epoch minutes) and cleaning times are a
"previous product id -> timedelta" map. The line's job_ids order is the
source of truth for the assignment, and each job's line_id / start_cleaning_date_time /
start_production_date_time / end_date_time are result-only fields
(ignored by to_core)::
from optimaru.food_packaging.models import PackagingScheduleModel
model = PackagingScheduleModel.from_core(schedule) # engine -> pydantic
clone = PackagingScheduleModel.model_validate_json(model.model_dump_json())
schedule2 = clone.to_core() # pydantic -> engine
ProductModel ¶
Bases: StrictModel
A product. cleaning_durations maps a previous product to the cleaning time: keys are the id of the product made on the line 'just before'. When a (previous, current) pair without an entry actually ends up adjacent, it is an error.
JobModel ¶
Bases: StrictModel
A packaging job (an element of a line's job list). LineModel.job_ids is the source of truth for the assignment; line_id and start_cleaning/start_production/end are result-only derived fields (ignored by to_core). min_start_time and priority are read by no constraint.
LineModel ¶
Bases: StrictModel
A production line. job_ids is the decision (the line's jobs, order matters); operator_id is the second decision, the line's operator.
PackagingScheduleModel ¶
Bases: StrictModel
The whole schedule. The score is a read-only result, kept as separate fields. Jobs in no line's job_ids are unassigned (the solver leaves pinned unassigned jobs alone, and the rest can get assigned on a re-solve).
PackagingScheduleRequest ¶
Bases: SolveRequest
The packaging schedule with the settings of one solve (see SolveRequest for those).
datetime_to_minute ¶
datetime_to_minute(value: datetime) -> int
naive datetime -> epoch minutes (from 1970-01-01T00:00).
with_initial_solution ¶
with_initial_solution(problem: PackagingScheduleModel, solution: PackagingScheduleModel | dict) -> PackagingScheduleModel
Return a copy of problem whose search starts from solution.
solution is what a solve returned, as the model or as its JSON dict. Each
line's job_ids and operator_id become the ones it has there, replacing
what problem had; a line the solution leaves out starts empty, with no
operator. Lines and jobs are matched by id. Only those two fields are read:
the jobs' pins, the facts and the derived fields stay as problem has them.
Jobs in no line are placed by construction, which may also leave them in the
unassigned pool when that scores best. A solution that assigns every job is
the exact starting point of the job lists, with two limits on the default
solve (fp.solve without constraints=):
- The operators are not fixed.
improve_operator_assignmentruns after the search even with no time to search, and moves a seeded operator whenever that strictly cuts the cleaning conflict. Theconstraints=solve never moves one. - A time limit of 1 ms or less returns before construction, so jobs left out stay unassigned. Give it any longer limit to have them placed.
Pinned jobs stay problem facts: a line in solution must start with the
pinned jobs it has in problem, and no other pinned job may appear. Raises
ValueError otherwise, on an unknown line, job or operator, on a line or job
given twice, and on a job following another with no cleaning time between
their products, which would otherwise throw in the middle of a solve.
solve_request ¶
solve_request(request: PackagingScheduleRequest, *, constraints=None) -> PackagingScheduleModel
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(schedule: PackagingScheduleModel) -> list[ParameterUse]
The parameters schedule sets away from their defaults that act only through a cost.
None in this use case: a job's time window and ideal end are required fields, and a
line's operator is a decision. (JobModel.min_start_time and priority are read by no
constraint at all.) fp.solve still runs the check, so the rule reads the same in every
use case; the table is in the use-case guide ("Parameters and their costs",
docs/use-cases/README.md).
optimaru.food_packaging.constraints ¶
Constraint assembly specs — an API for picking the cost function declaratively.
The default path (fp.solve(schedule)) enables all five constraints at the 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(schedule, constraints=...).
A constraint list reads one way: one class call per constraint::
import optimaru.food_packaging as fp
from optimaru.food_packaging.constraints import (
MaxEndTimeCost, SquaredMakespanCost, UnassignedJobsCost, get_constraints,
)
fp.solve(schedule, constraints=get_constraints()) # the defaults as-is
fp.solve(schedule, constraints=[ # picked
MaxEndTimeCost(), UnassignedJobsCost(), SquaredMakespanCost(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: max_end_time_cost is
MaxEndTimeCost(), and so on.)
Every spec takes five knobs:
weightlinear multiplier on the constraint cost, in units of its level.None= the component default (fp.constraint_info()reports them).levelNone= the default level, otherwise aLevelor its name (Level.MEDIUMor"medium"). Any flippable constraint may take any of the three levels.AfterIdealEndTimeCostandUnassignedJobsCostare MEDIUM constraints by default:level="hard"makes them one hard unit per minute andlevel="soft"one soft unit per minute (outside the 10^10 medium fold), in the solver and in :func:scorealike. Aweightis in units of the level in effect.exponentsign-preserving power shaping:weight * sign(c) * |c| ** exponent, per line for the unit constraints and on the single total for the globalsOperatorCleaningConflictCostandUnassignedJobsCost. 2.0 = squared, so concentrated violations grow much costlier.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 line below the offset lowers the penalty. The literal form charges every unit the constraint evaluates, a raw 0 included: every line (an empty one included, never the unassigned pool, which is no line) for the per-line constraints, the one total for a global; aconstraint_costs()entry lists the lines as"units". With an offset it is refused on hard (MaxEndTimeCostandOperatorCleaningConflictCostby default), because hard 0 must mean no violation; medium folds into soft here, so it takes the literal formula.
The same constraint may be picked several times; each pick is scored on its own with its own knobs and the picks add up. Lateness past the deadline per line, plus its square beyond 30 minutes::
fp.solve(schedule, constraints=[
MaxEndTimeCost(),
MaxEndTimeCost(exponent=2, offset=30),
*[spec for spec in get_constraints() if spec.name != "max_end_time_cost"],
])
fp.constraint_costs(schedule, picks) keys the second pick "max_end_time_cost#2".
Names (name) are the C++ component names in snake_case
(MaxEndTimeCost -> max_end_time_cost). The core derives them mechanically,
so there is no hand-maintained alias table — check them with fp.list_constraints().
Module-level instance names use the same snake_case, so they match the strings
list_constraints() prints.
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.
MaxEndTimeCost
dataclass
¶
Bases: Constraint
Minutes by which a job passes the end time it must not miss. Default: hard, weight 1.
Unassigned jobs are silent here — unassigned_jobs_cost prices them.
AfterIdealEndTimeCost
dataclass
¶
Bases: Constraint
Minutes by which a job passes its ideal end time. Default: medium, weight 1 (medium units).
Missing the ideal time is a cost; missing max_end_time_cost is a violation —
that is why the shape is the same but the level differs. The domain folds medium
into the engine soft level as medium * 10^10; the fold belongs to the domain
(every constraint_costs() entry carries it as medium_fold), so the weight
carries no 10^10 factor.
SquaredMakespanCost
dataclass
¶
Bases: Constraint
The square of each line's busy time. Default: soft, weight 1.
Squaring pushes toward spreading jobs evenly across lines rather than just shrinking the total. An empty line costs nothing.
The square lives inside the raw cost rather than in exponent on purpose — the
exponent shapes the raw cost on top of it, so callers can still layer more shaping.
OperatorCleaningConflictCost
dataclass
¶
Bases: Constraint
Overlapping cleaning minutes on lines sharing one operator. Default: hard, weight 1.
One person cannot clean two machines at once. The conflicting jobs sit on different lines, so this is a global constraint (two jobs on one line have strictly sequential cleaning windows and cannot overlap).
UnassignedJobsCost
dataclass
¶
Bases: Constraint
Production minutes of jobs on no packaging line. Default: medium, weight 1 (medium units).
Dropping a long job hurts more than dropping a short one. A job can be in no list
at all (the initial state before the construction heuristic), so the condition is
"on no line", which is global rather than a property of any single unit. The
domain's medium fold (medium * 10^10 into soft) lives in the domain, not in the
weight.
get_constraints ¶
get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]
Return the cost function. Without arguments, all five default constraints.
When constraints is given, that list is used as-is — only the listed
constraints are scored::
get_constraints([MaxEndTimeCost(), SquaredMakespanCost(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 fp.constraint_costs(schedule) returns: per constraint, the
raw cost of each unit (before weight, exponent, offset and level rounding).
Fetch it once and rescore with different weights without re-solving::
raw = fp.constraint_costs(schedule)
score(raw) # default set
score(raw, [MaxEndTimeCost(), SquaredMakespanCost(weight=10)])
score(raw, [MaxEndTimeCost(), MaxEndTimeCost(exponent=2, offset=30)])
No solver and no search are involved. The arithmetic matches the engine —
each 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). 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.
The returned value is the engine-level (hard, soft): the domain's medium
fold (medium_fold on every entry, into soft at 10^10) is applied, so it
equals (score.hard, score.medium * 10**10 + score.soft) of a schedule scored
by the same constraints.
optimaru.food_packaging._core ¶
Typed stubs for the pybind11 extension optimaru.food_packaging._core.
Score convention (three levels, hard / medium / soft; all penalties), at the default weights (the C++ components' kDefaultWeight, see constraint_info()): hard 1. max_end_time_cost minutes past Job.max_end_time, x -1 hard 2. operator_cleaning_conflict_cost overlapping cleaning minutes on lines of one operator, x -1 (global) medium 3. after_ideal_end_time_cost minutes past Job.ideal_end_time, x -1 (medium units) medium 4. unassigned_jobs_cost duration minutes of jobs on no line, x -1 (medium units, global) soft 5. squared_makespan_cost (end of a line's last job - line start)^2, x -1
Internally the engine uses Score(int64 hard, double soft), mapped as
engine.soft = medium * 10**10 + soft (the domain's medium fold, "into_soft" with unit
1010; level priority holds while |soft| < 1010 and |medium| < 9 * 105; see
cpp/fp/model/domain.hpp). Medium weights are in medium units: the two medium
constraints' default weight is 1, not 1010.
SolverConfig ¶
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
0 = auto: clamp(8 * unpinned job 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.
nearby_probability
instance-attribute
¶
nearby_probability: float
Bias swap partners and relocate insertion points toward cheap-changeover neighbors (the cleanup matrix) with this probability; 0.8 by default, 0 = off (uniform selection).
nearby_size
instance-attribute
¶
nearby_size: int
Neighbors kept per job for nearby selection (10 by default).
on_new_best
instance-attribute
¶
on_new_best: Callable[[int, Score], None] | None
Progress callback (steps, best score). The score has the same three levels as the final schedule.score: with solve_with_constraints both come from the chosen constraints' hard / medium / soft totals, so a soft total of 10^10 or more stays on soft instead of spilling into medium.
Solver ¶
solve_with_constraints ¶
solve_with_constraints(schedule: PackagingSchedule, constraints: Iterable[Any] | None = ...) -> None
Score the same solve with a caller-chosen constraint set (see optimaru.food_packaging.constraints). The given list replaces the default set; None keeps the default set. 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. schedule.score reports the three levels the assembly put the terms on (a medium constraint with level="soft" lands on soft, a soft one with level="medium" on medium).
ConstraintInfo ¶
Bases: NamedTuple
One constraint-catalog row, read off the C++ default assembly.
list_constraints ¶
list_constraints() -> list[str]
Constraint names scored by this domain (default assembly order, snake_case: the unit constraints, then the globals operator_cleaning_conflict_cost and unassigned_jobs_cost). The same names optimaru.food_packaging.constraints uses.
constraint_costs ¶
constraint_costs(schedule: PackagingSchedule, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]
Raw per-unit 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, "units": [...],
"medium_fold": {"kind": "into_soft", "unit": 1e10}}}. Units are the lists (the
packaging lines in order, then the unassigned pool); a global constraint has one
entry and no "units". A per-line constraint's "units" are the lines it evaluates
(every line, never the pool), where a literal offset (clip=False) charges a raw 0.
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
"medium_fold is on EVERY entry (the fold belongs
to the domain), and optimaru.food_packaging.constraints.score() applies it. The only
per-constraint surface.
constraint_info ¶
constraint_info() -> list[ConstraintInfo]
The constraint catalog, in list_constraints() order: each component's default level and weight (in units of that level; after_ideal_end_time_cost and unassigned_jobs_cost are medium, weight 1), whether its level may be flipped, whether it is a reward, and whether it is scored when no constraints are given.