optimaru.task_assigning¶
Generated from the sources of optimaru/task_assigning/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.task_assigning ¶
Task assigning — Python wrapper of the C++ solver on the optimaru engine.
Customer/TaskType/Task/Employee/TaskAssigningSolution/Score/
Solver/SolverConfig and calculate_score come from the compiled C++ core (_core).
The decision variable is each Employee.tasks — the ordered list of task indices the
employee performs back to back. A task in no list is unassigned.
Derived values (recomputed by calculate_score/Solver.solve):
task.employee == index of the employee owning the list (-1 == unassigned)
task.start_time == the first task gets its own min_start_time,
later tasks max(end of the previous task, min_start_time)
duration == base_duration x affinity multiplier (HIGH 1 / MEDIUM 2 /
LOW 3 / NONE 4)
Score convention (four score levels, [1]hard/[3]soft; all penalties),
at the default weights:
hard[0] required_skill_cost required skills the employee lacks
soft[0] unassigned_tasks_cost 1 per unassigned task (the medium level)
soft[1] squared_makespan_cost endTime^2 per employee
soft[2] {critical|major|minor}_priority_task_end_time_cost
endTime x 4 / x 2 / x 1
Internally it maps onto Score(int64, double) as
engine.hard = hard * 10**9 + soft0 (the medium level folds below hard) and
engine.soft = soft1 * 10**7 + soft2 (squared_makespan_cost's default weight is 10**7);
level order preserved, see cpp/ta/model/domain.hpp for the exact rules.
constraint_info() lists every constraint with its default level and weight; change one
through a constraint selection (see optimaru.task_assigning.constraints).
The high-level entry point is solve::
import optimaru.task_assigning as ta
from optimaru.task_assigning.demo import generate_demo_data
solution = generate_demo_data() # models.TaskAssigningSolutionModel
result = ta.solve(solution, time_limit_seconds=10.0, random_seed=42)
print(result.score_hard, result.score_soft0, result.score_soft1, result.score_soft2)
The pydantic mirror (for serialization) is in optimaru.task_assigning.models.
optimaru.task_assigning.models ¶
Pydantic v2 mirror of the engine domain — for JSON serialization/deserialization.
Mirrors _core's TaskType/Customer/Task/Employee/TaskAssigningSolution 1:1, but
references are id/code strings
(task_type_code/customer_id; an employee's tasks is a list of task ids).
The engine conversion (to_core) turns references into indices::
from optimaru.task_assigning.models import TaskAssigningSolutionModel
model = TaskAssigningSolutionModel.model_validate_json(payload)
solution = model.to_core() # pydantic -> engine
...solve...
solved = TaskAssigningSolutionModel.from_core(solution) # engine -> pydantic
The assignment lives on the employee side: employees[i].tasks is
the ordered list of task ids that employee performs. The task side carries the computed
start_time (None when unassigned).
TaskTypeModel ¶
Bases: StrictModel
A task type. base_duration is the base duration in minutes (before the affinity multiplier).
CustomerModel ¶
Bases: StrictModel
A customer (problem fact).
TaskModel ¶
Bases: StrictModel
One task to perform. Which employee does it is decided by
EmployeeModel.tasks (an ordered list of task ids).
start_time is the computed start (minutes; None when unassigned).
EmployeeModel ¶
Bases: StrictModel
An employee. tasks is the decision variable — the ordered
list of task ids this employee performs back to back. Customers missing from
customer_to_affinity count as NONE (multiplier 4).
TaskAssigningSolutionModel ¶
Bases: StrictModel
Pydantic mirror of the solution. score_* are read-only results, kept as separate fields (the four score levels, [1]hard/[3]soft).
to_core ¶
to_core() -> _core.TaskAssigningSolution
pydantic -> engine object (code/id references to indices; the score field is ignored since the engine recomputes it). Tasks in no employee list stay unassigned — the solver decides the assignment.
from_core
classmethod
¶
from_core(solution: TaskAssigningSolution) -> TaskAssigningSolutionModel
engine object -> pydantic (including the current assignment and score). Affinity omits NONE entries.
TaskAssigningRequest ¶
Bases: SolveRequest
The task assigning problem with the settings of one solve (see SolveRequest for those).
with_initial_solution ¶
with_initial_solution(problem: TaskAssigningSolutionModel, solution: TaskAssigningSolutionModel | dict) -> TaskAssigningSolutionModel
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
employee's tasks become that employee's tasks there, replacing what
problem had; an employee the solution leaves out starts empty. Employees
and tasks are matched by id.
Tasks in no list are placed by construction. A solution that assigns every task is the exact starting point. Raises ValueError on an unknown employee or task, or a task assigned twice.
parameter_uses ¶
parameter_uses(solution: TaskAssigningSolutionModel) -> list[ParameterUse]
The parameters solution sets away from their defaults that act only through a cost.
task_assigning.solve refuses a selection that holds none of a parameter's costs
(optimaru._constraint.require_costs); the table is in docs/use-cases/README.md
("Parameters and their costs").
solve_request ¶
solve_request(request: TaskAssigningRequest, *, constraints=None) -> TaskAssigningSolutionModel
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.task_assigning.constraints ¶
Constraint assembly specs — an API for picking the cost function declaratively.
The default path (ta.solve(solution)) enables all six 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(solution, constraints=...).
A constraint list reads one way: one class call per constraint::
import optimaru.task_assigning as ta
from optimaru.task_assigning.constraints import (
RequiredSkillCost, SquaredMakespanCost, UnassignedTasksCost, get_constraints,
)
ta.solve(solution, constraints=get_constraints()) # the defaults as-is
ta.solve(solution, constraints=[ # picked
RequiredSkillCost(), UnassignedTasksCost(), 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: required_skill_cost
is RequiredSkillCost(), and so on.)
Every spec takes five knobs:
weightlinear multiplier on the constraint cost, in units of its level.None= the C++ component default (ta.constraint_info()lists them).levelNone= the default level, otherwise aLevelor its name (Level.MEDIUMor"medium"). Any flippable constraint may take any of the three levels.UnassignedTasksCostis the one medium constraint by default (soft[0], folded into the engine's hard level BELOW the missing skills:engine.hard = hard * 10^9 + medium):level="hard"charges one hard unit (10^9 engine-hard units) per unassigned task,level="soft"one soft unit per unassigned task, and aweightis in units of the level in effect. A constraint moved onto medium counts in that below-hard level too, rounded per unit like a hard one.exponentsign-preserving power shaping:weight * sign(c) * |c| ** exponent, per employee for the unit constraints and on the total for the globalUnassignedTasksCost. 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 an employee below the offset — an idle one (cost 0) included — lowers the penalty. With an offset it is refused on hard (RequiredSkillCostby default) and on medium (UnassignedTasksCostby default), since medium folds below hard here and so counts toward the hard score, and 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. The critical end times per employee, plus the square of the part beyond 120 minutes::
ta.solve(solution, constraints=[
*get_constraints(),
CriticalPriorityTaskEndTimeCost(exponent=2, offset=120),
])
ta.constraint_costs(solution, picks) keys the second pick
"critical_priority_task_end_time_cost#2".
This domain scores four score levels (hard[0], soft[0..2]) on the engine's
three: hard (required_skill_cost), medium (unassigned_tasks_cost) and soft
(the other four). soft[1] and soft[2] share the soft level; the default weight 10^7 of
squared_makespan_cost is what keeps the makespan term above the priority end
times, so a weight you pass is a share within the same level (see cpp/ta/model/domain.hpp).
Names (name) are the C++ component names in snake_case
(RequiredSkillCost -> required_skill_cost). The core derives them
mechanically, so there is no hand-maintained alias table — check them with
ta.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.
RequiredSkillCost
dataclass
¶
Bases: Constraint
Skills the task type requires that the assigned employee lacks. Default: hard, weight 1.
hard[0]; the domain's below-hard fold puts one missing skill 10^9 engine-hard units above one unassigned task, so the weight is in plain hard units.
SquaredMakespanCost
dataclass
¶
Bases: Constraint
The square of each employee's end time. Default: soft, weight 10^7.
Squaring pushes toward taking work off the busiest employee rather than just shrinking the total. An employee without tasks ends at 0 and costs nothing. Level soft[1]: the default weight 10^7 keeps it above the priority end-time terms on the shared soft level.
The square lives inside cost() rather than in exponent on purpose: the exponent
shapes each unit's raw cost before the weight; here the square is the constraint's
own definition, so a caller can still shape it further.
CriticalPriorityTaskEndTimeCost
dataclass
¶
MajorPriorityTaskEndTimeCost
dataclass
¶
MinorPriorityTaskEndTimeCost
dataclass
¶
Bases: Constraint
End time of MINOR tasks. Default: soft, weight 1 — the baseline of the three priority constraints.
UnassignedTasksCost
dataclass
¶
Bases: Constraint
Tasks on no employee's list. Default: medium, weight 1.
soft[0], the domain's medium level: it folds into the engine's hard level
below the missing-skill count (engine.hard = hard * 10^9 + medium), which
dominates it lexicographically. Unassigned tasks belong to no unit, so
this is a global constraint.
get_constraints ¶
get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]
Return the cost function. Without arguments, all six default constraints.
When constraints is given, that list is used as-is — only the listed
constraints are scored::
get_constraints([RequiredSkillCost(), SquaredMakespanCost(weight=10)])
Same contract as the C++ applyConstraints: an empty list is an error (pass None for the defaults); 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 ta.constraint_costs(solution) returns: per constraint, the
raw cost of each unit (before weight, exponent, offset and level rounding),
its default weight and level, and the domain's medium fold (on every entry).
Fetch it once and rescore with different weights without re-solving::
raw = ta.constraint_costs(solution)
score(raw) # default set
score(raw, [RequiredSkillCost(), SquaredMakespanCost(weight=10)])
score(raw, [MinorPriorityTaskEndTimeCost(), MinorPriorityTaskEndTimeCost(exponent=2, offset=60)])
No solver and no search are involved. The arithmetic matches the engine —
each unit contributes weight * shape(cost, exponent, offset, clip) (a second
pick of a constraint reads the same raw costs with its own knobs), hard and medium
contributions are rounded per unit before summing, and the medium level
folds below hard: hard * 10^9 + medium (even when no medium constraint is
picked).
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 hard level carries
hard * 10^9 + soft0 and the soft level soft1 * 10^7 + soft2 at the default
weights, so to compare with the split levels of solution.score, fold the same way first.
optimaru.task_assigning._core ¶
Type stubs for optimaru.task_assigning._core — the task-assigning C++ solver.
The compiled module wraps the C++ domain in optimaru/task_assigning/cpp,
which imports the generic engine in core/optimaru.
The decision variable is each Employee.tasks (sequence shape): the ordered list of task
indices the employee performs back to back. A task in no list is unassigned.
The derived values Task.employee (-1 == unassigned) / Task.start_time (-1 == unassigned)
are recomputed from the lists by calculate_score / Solver.solve.
Score convention (four score levels, [1]hard/[3]soft; all penalties), at the default weights (constraint_info()): hard[0] required_skill_cost required skills the employee lacks (hard, 1) soft[0] unassigned_tasks_cost 1 per unassigned task (medium, 1) soft[1] squared_makespan_cost endTime^2 per employee, end of the last task (soft, 10**7) soft[2] critical_priority_task_end_time_cost endTime x 4 (soft, 4) major_priority_task_end_time_cost endTime x 2 (soft, 2) minor_priority_task_end_time_cost endTime x 1 (soft, 1)
Internally the engine uses Score(int64 hard, double soft). The medium level (soft0) folds below hard and the soft level packs soft1 above soft2: engine.hard = hard * 109 + soft0 (medium_fold {"kind": "below_hard", "unit": 1e9}) engine.soft = soft1 * 107 + soft2 (squared_makespan_cost's default weight 107) (level priority holds while |soft0| < 109, |soft2| < 107, |soft1| < 9x108; see cpp/ta/model/domain.hpp for the exact rules).
Score ¶
Four-level score, [1]hard/[3]soft. hard 0 == feasible (unassigned is soft0). Lexicographic comparison (hard > soft0 > soft1 > soft2).
Affinity ¶
Bases: Enum
Employee-customer affinity. Duration multiplier: HIGH 1 / MEDIUM 2 / LOW 3 / NONE 4.
Priority ¶
Bases: Enum
endTime penalty weight: CRITICAL 4 / MAJOR 2 / MINOR 1 (soft[2]).
Customer ¶
Problem fact: a customer.
TaskType ¶
Problem fact: a task type. base_duration is in minutes (before the affinity multiplier).
Task ¶
One task (the sequence element). task_type/customer are indices into the solution lists.
Employee ¶
An employee. tasks is the decision variable (ordered
task indices). Reading it from the solution returns a copy — bulk-write with
TaskAssigningSolution.set_task_lists.
TaskAssigningSolution ¶
The problem and its solution. The constructor validates index references and the integrity of the task lists (ranges, duplicate assignment).
SolverConfig ¶
best_score_limit
instance-attribute
¶
best_score_limit: tuple[int, int, int, int]
(hard, soft0, soft1, soft2): stop early once bestScore >= this. -(263) on soft1 or soft2 means no floor there (only hard and soft0 are compared), so (0, 0, -(263), -(2**63)) stops at the first solution with every skill met and every task assigned.
Solver ¶
solve ¶
solve(solution: TaskAssigningSolution) -> None
Solves in place: relocates employees[*].tasks and refreshes the derived task fields and solution.score.
solve_with_constraints ¶
solve_with_constraints(solution: TaskAssigningSolution, constraints: Iterable[Any] | None = ...) -> None
Score the same solve with a caller-chosen constraint set (see optimaru.task_assigning.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. A pick moved onto medium lands on soft0 (below hard).
ConstraintInfo ¶
Bases: NamedTuple
One constraint-catalog row, read off the C++ default assembly.
calculate_score ¶
calculate_score(solution: TaskAssigningSolution) -> Score
Full recompute of the four-level score at the default weights (recomputes the derived task fields + stores solution.score).
list_constraints ¶
list_constraints() -> list[str]
Constraint names scored by this domain (default assembly order, snake_case; the unit constraints first, the global unassigned_tasks_cost last): required_skill_cost, squared_makespan_cost, critical_priority_task_end_time_cost, major_priority_task_end_time_cost, minor_priority_task_end_time_cost, unassigned_tasks_cost. The same names optimaru.task_assigning.constraints uses.
constraint_costs ¶
constraint_costs(solution: TaskAssigningSolution, constraints: Iterable[Any] | None = ...) -> dict[str, dict[str, Any]]
Raw per-employee cost of every constraint (one total for the global
unassigned_tasks_cost), 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,
"medium_fold": {"kind": "below_hard", "unit": 1e9}}}. Every employee is a unit the
per-employee constraints evaluate, an idle one included (a literal offset,
clip=False, charges it). 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 "optimaru.task_assigning.constraints.score() turns it into the
engine score.
constraint_info ¶
constraint_info() -> list[ConstraintInfo]
The constraint catalog, in list_constraints() order: required_skill_cost (hard, 1), squared_makespan_cost (soft, 1e7), critical_priority_task_end_time_cost (soft, 4), major_priority_task_end_time_cost (soft, 2), minor_priority_task_end_time_cost (soft, 1), unassigned_tasks_cost (medium, 1); all flippable, none a reward, all scored by default (default_enabled).