optimaru.employee_scheduling¶
Generated from the sources of optimaru/employee_scheduling/ and the stubs of its compiled
extension. The guide explains the model and the constraints in prose.
optimaru.employee_scheduling ¶
Employee shift scheduling — C++ wrapper on the optimaru engine, with Python helpers.
Employee, Shift, EmployeeSchedule, Score, Solver, SolverConfig,
calculate_score, constraint_costs, constraint_info and minutes come from
the compiled pybind11 module (_core). The cost function is assembled from
constraint specs (see constraints.py, one class per constraint):
DecomposedCalculator([RequiredSkillCost(), UndesiredDayCost(weight=2.0), ...])
— or by name via DecomposedCalculator().add("undesired_day_cost", weight=2.0) /
default_calculator(). constraint_info() lists all 30 constraints with their
C++ default level and weight (the eight defaults first); list_constraints()
the names the constraint factory accepts. solve(schedule, ...) solves a schedule in
place and returns it; make_random_roster, summary and to_dataframe are
pure-Python conveniences.
The JSON-friendly request/solution layer is optimaru.employee_scheduling.models (pydantic);
optimaru.employee_scheduling.demo.generate_demo_data builds a sample request and
with_initial_solution restarts a solve from an earlier result.
optimaru.employee_scheduling.models ¶
Pydantic request/response models — JSON-friendly in/out for the solver.
Defines a request carrying workers, shifts, and a discriminated list of constraints, plus a response with a per-worker schedule and violation report:
from optimaru.employee_scheduling.constraints import MaxConsecutiveDaysCost, RequiredSkillCost
from optimaru.employee_scheduling.models import (
ScheduleRequest, SchedulingInput, WorkerModel, ShiftModel, solve_request,
)
request = ScheduleRequest(
time_limit_seconds=2,
model_input=SchedulingInput(
workers=[WorkerModel(id="Worker 01", skills=["Skill A"])],
shifts=[ShiftModel(id="Shift 1", start=540, end=1020, required_skill="Skill A")],
constraints=[RequiredSkillCost(), MaxConsecutiveDaysCost(value=6, weight=2)],
),
)
solution = solve_request(request) # -> ScheduleSolution
print(solution.schedule) # {"Worker 01": [ShiftAssignmentModel(...)]}
print(solution.model_dump_json(indent=2))
Everything round-trips through JSON (ScheduleRequest.model_validate_json,
solution.model_dump_json), so this doubles as a service API contract. A constraint
in JSON is {"name": "max_consecutive_days_cost", "weight": 2, "value": 6}:
the spec's name, its knobs (weight / level / exponent /
offset / clip) and its domain parameters.
There is ONE class per constraint: the spec in optimaru.employee_scheduling.constraints.
The JSON constraint models (CONSTRAINT_MODELS, the ConstraintModel union; one generated pydantic
model per spec, named <Spec>Model, e.g. MaxConsecutiveDaysCostModel)
are generated from the specs' fields and bounds, so they cannot drift from
them; SchedulingInput.constraints accepts spec instances and JSON dicts alike (on
construction and on assignment), and constraint.to_spec() turns a validated constraint
back into its spec. A constraint may appear several times (each entry is its own
instance with its own knobs, and the instances add up); an empty constraint list is
refused, as get_constraints() refuses it.
Times are integer minutes from day 0, 00:00 (see optimaru.employee_scheduling.minutes);
dates are day indices.
A solve can start from an earlier result: with_initial_solution(request,
solution) returns a new request whose ShiftModel.worker fields carry that
result, and construction then fills only the shifts it left out.
WorkerModel ¶
Bases: StrictModel
One person who can be assigned to shifts.
ShiftModel ¶
Bases: StrictModel
One shift to be covered by exactly one worker.
ConstraintModelBase ¶
Bases: BaseModel
One constraint as JSON: the spec's knobs and parameters; to_spec() is the spec.
weight None = the component's default weight; level None = its
default level, otherwise "hard" or "soft"; exponent > 0 shapes the cost;
offset (finite, any sign) shifts that shaping and clip says what
happens below the offset (True: only what lies beyond it counts; False:
the literal (cost - offset) ** exponent). A constraint is also a valid pick
for DecomposedCalculator (it carries name / weight / level /
exponent / offset / clip and params()). The knobs take the
values the spec takes: weight: true or "2" is refused here as the
spec refuses it. clip: false with a non-zero offset is refused on
hard (the constraint's level, or its default level), in the engine's words,
because hard 0 must mean no violation. Unknown keys are refused.
SchedulingInput ¶
ScheduleRequest ¶
Bases: SolveRequest
The scheduling problem with the settings of one solve (see SolveRequest for the shared ones).
parallel_solver_count (alias num_workers) and settings.multi_start ask for the
same thing, independent starts in parallel processes: the larger of the two applies,
and each start gets the full time_limit_seconds. settings holds the search
options of this use case. Its random_seed and stop_at_first_feasible are the
request's own fields under another name. When the request is built, one given at the
top level wins and one given only in settings is taken up, so both say the same.
After that, a value set at the top level is the one used; until one is set there,
a change to settings is. A request read back from its own JSON has the top-level
fields set, so there the top level is the one to change. A dump writes the value in
use to both places.
solver_parameters are applied after settings, so a field named in both takes the
value in solver_parameters. Two things come later still and win over it: the stop
target (settings.best_score_limit, or stop_at_first_feasible) and the per-start
settings.portfolio overrides. The request keeps a synced copy of the settings it
was built with, so change request.settings, not the object that was passed in.
ConstraintTotal ¶
Bases: BaseModel
Weighted cost of one constraint instance in the final schedule (positive =
penalizing, negative = rewarding) — the score explanation. name is the
constraint name ("shift_coverage_cost"); label tells the instances
of a parametrized constraint apart ("Shift coverage[Skill A 1..inf]"; empty
for a constraint without one).
ScheduleSolution ¶
Bases: BaseModel
rule_totals
property
¶
rule_totals: list[ConstraintTotal]
Alias of constraint_totals, the name of earlier versions.
constraint_model ¶
constraint_model(constraint: str | type[Constraint]) -> type[ConstraintModelBase]
The JSON constraint model of a constraint, by name or spec class.
default_constraints ¶
default_constraints() -> list[ConstraintModelBase]
The eight default constraints at their default weights (equal to the built-in score).
to_schedule ¶
to_schedule(model_input: SchedulingInput) -> _core.EmployeeSchedule
Build the C++ EmployeeSchedule from the pydantic input (pre-assigned
shift.worker ids become the starting assignment).
with_initial_solution ¶
with_initial_solution(problem: ScheduleRequest, solution: ScheduleSolution | Mapping[str, Any]) -> ScheduleRequest
A new request whose solve starts from solution; problem is not changed.
solution is what solve_request returns: a ScheduleSolution or the plain
dict of model_dump(mode="json"). Workers and shifts are matched by id, never
by position, and an assignment is read for its shift_id only.
Each shift's ShiftModel.worker becomes what the solution says, so the solve
starts there instead of constructing it. A partial solution is fine: a shift
it leaves out, or lists as unassigned, loses any earlier worker and is
placed by normal construction, and nothing else is. A complete solution leaves
construction nothing to do. Local search may still move a shift afterwards;
use pinned to fix one.
A pinned shift keeps its worker, whether the solution mentions it or not.
Raises ValueError, naming the worker or shift, for an unknown id, a shift assigned twice or both assigned and unassigned, a malformed assignment, or a pinned shift the solution moves away from its worker or unassigns.
parameter_uses ¶
parameter_uses(model_input: SchedulingInput) -> list[ParameterUse]
The parameters model_input sets away from their defaults that act only through a cost.
solve_request refuses a request whose constraints (model_input.constraints, or the
constraints it is given) hold none of a parameter's costs
(optimaru._constraint.require_costs). desired_shift_cost is off by default, so a
worker's desired_shifts needs it picked. The table is in the use-case guide
("Parameters and their costs", docs/use-cases/README.md).
solve_request ¶
solve_request(request: ScheduleRequest, *, constraints=None, select: Callable[[list[ScheduleSolution]], ScheduleSolution] | None = None) -> ScheduleSolution
Solve a pydantic request end-to-end and return the pydantic solution.
constraints, a list of constraint specs (see optimaru.employee_scheduling.constraints)
as solve takes it, replaces request.model_input.constraints for this solve; None scores
the request's own constraints. The request is not changed.
request.parallel_solver_count or settings.multi_start > 1 runs that many
independent solves (the larger of the two; seeds random_seed + i) in
parallel processes and returns the best-scoring one. Each start gets the
full time_limit_seconds and at most one start per core runs at a time. The
metaheuristic has real run-to-run variance, so best-of-n is a cheap,
reliable quality lift (and uses the extra cores). 1 (default) is a single
solve.
Parallel starts are forked. Forking a process that runs other threads is unsafe: the child gets a copy of any lock another thread held and can hang on it, Python 3.12+ warns with a DeprecationWarning, and macOS system libraries may abort in the child. From a threaded host, call this in a subprocess of its own, or stay at one start. A single start does not fork, and releases the GIL while it solves.
Where processes cannot be used (no fork, a daemonic process) or a worker
dies, the starts run one after another, so the wall time can reach n times
time_limit_seconds. An error raised by a start is not retried.
select lets the caller pick the best-of-n candidate itself (given the
full list of solutions) instead of the built-in faithful-score key -- e.g.
to rank candidates on an external objective the internal score only
approximates. Ignored for a single start.
A request that sets a parameter whose costs its constraints leave out is refused with
ValueError (parameter_uses): the solve would not score it. es.solve on a compiled
schedule is not checked.
optimaru.employee_scheduling.constraints ¶
Constraint specs — one class per constraint of the employee-scheduling engine.
Each spec names one C++ component (name is its Python registry name, the
C++ name in snake_case) and carries the five knobs every optimaru constraint
takes, plus the constraint's own domain parameters::
constraints = [
RequiredSkillCost(), # hard, default weight
MinRestCost(weight=0.25, level="soft"), # demoted to a cheap soft cost
UndesiredDayCost(weight=2.0, per_day=True), # soft, double weight, 1 per day
ShiftCountImbalanceCost(exponent=2.0),
MaxConsecutiveDaysCost(value=5, worker_indices=(0, 1)), # scoped
DayPatternCost(pattern="Location A,OFF,Location B"),
DayPatternCost(pattern="WORK,WORK,WORK,WORK,WORK,WORK,WORK"), # same constraint, again
UndesiredDayCost(weight=0.01, exponent=2, offset=120), # + (minutes beyond 2 h)^2
]
solver.solve(schedule, DecomposedCalculator(get_constraints(constraints)))
The knobs (see _constraint.py):
weightNone= the component's default weight (C++ kDefaultWeight; 1 for every employee-scheduling constraint); otherwise a finite number >= 0.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, > 0: per employee for a unit constraint, on the single total for a global one.offset(keyword) a shift of that shaping, any finite number (0.0 = none), at the same granularity.clip(keyword)True(the default, the threshold) counts only what lies beyond the offset,sign(c) * max(0, |c| - offset) ** exponent;False(the literal formula) shapesc - offsetas it is, which charges every employee the constraint evaluates (a raw 0 included; a worker-scoped constraint evaluates only the employees in its scope) and rewards a cost below the offset. With an offset it is refused on hard (the pick's level, or the default:RequiredSkillCostand the other hard constraints), because hard 0 must mean no violation.
The defaults live in C++ only; optimaru.employee_scheduling.constraint_info() reports
them for all 30 constraints. Every other field is a domain parameter
(spec.params()), including the constraint scope worker_indices /
shift_indices (engine indices; None = everyone) of the unit
constraints and of ShiftCoverageCost. A domain parameter's bounds are
declared once, in the class's bounds, and checked here; the JSON constraint
models (optimaru.employee_scheduling.models) are generated from these classes and turn
the same bounds into pydantic constraints.
One constraint may be picked several times, with different parameters, scope
or knobs, its level included (x**2 + x**3 is two picks, exponent=2
and exponent=3) or with the same ones (identical picks simply count
twice); the C++ factory scores each instance on its own,
constraint_totals() tells them apart by label and constraint_costs()
keys the k-th instance "<name>#<k>".
(The module also carries ready-made default instances: required_skill_cost
is RequiredSkillCost(), and so on.)
This module does not need pydantic.
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: _Scoped
1 per assigned shift whose required skill the employee lacks. Default: hard, weight 1.
EmployeeUnavailabilityCost
dataclass
¶
Bases: _Scoped
Minutes of assigned shifts on the employee's unavailable days. Default: hard, weight 1.
ShiftOverlapCost
dataclass
¶
Bases: _Scoped
Overlap minutes between two shifts of the same employee. Default: hard, weight 1.
MaxOneShiftPerDayCost
dataclass
¶
Bases: _Scoped
1 per PAIR of same-employee shifts starting on the same day. Default: hard, weight 1.
MinRestCost
dataclass
¶
Bases: _Scoped
Rest shortfall below min_gap_minutes (default 600 = 10 hours) between two
same-employee shifts. Default: hard, weight 1.
UndesiredDayCost
dataclass
¶
Bases: _Scoped
Minutes on the employee's undesired days, or 1 per such shift with per_day.
Default: soft, weight 1.
DesiredDayCost
dataclass
¶
Bases: _Scoped
Reward: minus the minutes on the employee's desired days, or minus 1 per such
shift with per_day (raw <= 0; never hard). Default: soft, weight 1.
DesiredShiftCost
dataclass
¶
Bases: _Scoped
Reward: minus 1 per assigned shift whose (day, location) the employee asked for
in desired_shifts — the location must match, not just the day (raw <= 0;
never hard). Default: soft, weight 1.
ShiftCountImbalanceCost
dataclass
¶
Bases: _EsConstraint
Load-balancing unfairness of the per-employee shift counts, sqrt(sum of squared deviations) (global). Default: soft, weight 1.
MaxConsecutiveDaysCost
dataclass
¶
Bases: _Scoped
Days beyond value in any run of consecutive worked days (value=6: "at most 6
days in a row"). Default: hard, weight 1.
MinConsecutiveDaysCost
dataclass
¶
Bases: _Scoped
Shortfall below value of any run of consecutive worked days ("if you work,
work at least value days in a row"). Default: soft, weight 1.
MaxConsecutiveDaysOffCost
dataclass
¶
Bases: _Scoped
Interior runs of more than value consecutive days off (bounded by work on both
sides; off days at the horizon edge are not counted). Default: soft, weight 1.
RestAfterConsecutiveWorkCost
dataclass
¶
Bases: _Scoped
After >= work_days consecutive worked days, the shortfall of the following rest
below rest_days (a run at the end of the horizon is not counted). Default: hard,
weight 1.
MaxWeeklyMinutesCost
dataclass
¶
Bases: _Scoped
Assigned minutes beyond minutes in any calendar week (7-day blocks from
week_anchor; a shift counts fully in its start week). 2400 = a 40-hour week.
Default: hard, weight 1.
MinWeeklyMinutesCost
dataclass
¶
Bases: _Scoped
Shortfall below minutes in EVERY calendar week of the horizon (7-day blocks
from week_anchor; an idle week costs the full threshold). Default: soft,
weight 1.
MinWeeklyRestDaysCost
dataclass
¶
Bases: _Scoped
Worked days beyond 7 - value in any calendar week (7-day blocks from day 0) —
"at least value rest days per week". Default: hard, weight 1.
AssignmentCost
dataclass
¶
Bases: _Scoped
Money: per (employee, shift) the shift_costs[employee_name][shift_id] entry if
present, else cost_per_hour * hours, else cost_per_shift. Default: soft,
weight 1.
UnassignedShiftsCost
dataclass
¶
Bases: _EsConstraint
1 per shift with no employee assigned (coverage guarantee; global). Default: hard, weight 1.
ShiftCountGapCost
dataclass
¶
Bases: _EsConstraint
Busiest-vs-least-busy shift-count gap beyond tolerance (global). Default: soft,
weight 1.
WeeklyMinutesGapCost
dataclass
¶
Bases: _EsConstraint
Per calendar week, the busiest-vs-least-busy gap of assigned minutes beyond
tolerance_minutes, in HOURS (global; all employees compared). Default: soft,
weight 1.
ShiftCoverageCost
dataclass
¶
Bases: _EsConstraint
Per (day, location) group, the count of assignees holding worker_skill (empty =
anyone) outside [min_count, max_count] (max_count < 0 = no cap; global).
Default: soft, weight 1.
Scoped natively: shift_indices restrict which shifts form groups and
worker_indices which employees count; here None OR an empty tuple
means everyone / every shift.
LocationRunLengthCost
dataclass
¶
Bases: _Scoped
Each maximal run of days at location (empty = any work) within [min_run,
max_run] (max_run < 0 = no cap); shorter/longer runs cost the shortfall/excess.
Default: soft, weight 1.
RestAfterLocationRunCost
dataclass
¶
Bases: _Scoped
After any run of location days, the worked days among the next rest_days
days (which must be fully off). Default: hard, weight 1.
LocationRunGapCost
dataclass
¶
Bases: _Scoped
Consecutive runs of location at least min_gap days apart; the shortfall per
too-close pair. Default: soft, weight 1.
WorkerLocationCountCost
dataclass
¶
Bases: _Scoped
Per employee holding worker_skill (empty = all), the count of location
shifts over the horizon outside [min_count, max_count] (max_count < 0 = no
cap). Default: soft, weight 1.
DayPatternCost
dataclass
¶
Bases: _Scoped
1 per window matching an ordered day pattern: comma-separated tokens, each a
location, "OFF" (off day), "*" (any day), "WORK" (any worked day) or "!x" (a
worked day not at location x). Example: "Location A,OFF,Location B". Default:
soft, weight 1.
TargetDaysOffCost
dataclass
¶
Bases: _Scoped
Per employee, the shortfall below min_count days off among target_days (day
indices, e.g. weekends / holidays). Default: soft, weight 1.
WorkerDayCountInRangeCost
dataclass
¶
Bases: _Scoped
Distinct worked days (at location; empty = any) in the day range [lo, hi]
outside [min_count, max_count] (max_count < 0 = no cap). Usually scoped to
one worker via worker_indices: "off >= K over a window" == "worked <=
window length - K". Default: soft, weight 1.
LocationImbalanceCost
dataclass
¶
Bases: _EsConstraint
Fairness of a per-employee count across employees holding worker_skill (empty =
all): location shifts (empty = all work), or the days off among
off_target_days when given. metric "ssd" (sqrt of squared deviations) or
"gap" (max - min beyond tolerance; global). Default: soft, weight 1.
WorkerPairingCost
dataclass
¶
Bases: _EsConstraint
A directional worker pairing over the (bucket_days, bucket_locations)
buckets both workers are eligible for. penalty=False: they should share the
same shift, so a bucket where exactly one works it costs 1; penalty=True:
they should not, so a bucket where both work it costs 1. Raw >= 0 in both modes
(not a reward). anchor / paired are engine worker indices (global).
Default: soft, weight 1.
instance_keys ¶
instance_keys(constraints: Iterable[Any]) -> list[str]
The constraint_costs() key of each pick, in order.
The name itself, and "<name>#<k>" for the k-th pick (k >= 2) of a name
the selection states several times: the rule the C++
constraint_costs() (python::instanceKeys) keys its entries by, given
the same list in the same order.
get_constraints ¶
get_constraints(constraints: list[Constraint] | None = None) -> list[Constraint]
The cost function, as a list of specs. No argument = the eight defaults.
The same entry point every use case in this repo exposes, so "start from the defaults and change one thing" reads the same everywhere::
from optimaru.employee_scheduling.constraints import UndesiredDayCost, get_constraints
solver.solve(schedule, DecomposedCalculator(get_constraints()))
solver.solve(schedule, DecomposedCalculator(get_constraints([
RequiredSkillCost(), UndesiredDayCost(weight=2.0),
])))
Passing constraints uses that list as given — only what is in it is
scored. An empty list is an error, not "the defaults". A constraint may
appear several times, with different parameters (scope included) or
knobs, or with the same ones: every pick is its own instance, scored on
its own, and the instances add up.
score ¶
score(costs: dict, constraints: list[Constraint] | None = None) -> Score
Score raw constraint costs with a selection — pure Python, the engine's arithmetic.
costs must be constraint_costs(schedule, constraints) of the SAME
list (repeated constraints are keyed "<name>#<k>"); None = the defaults on
both sides. Each spec's weight / level / exponent / offset / clip re-prices
its entry without another scoring pass. A repeat of a constraint without domain
parameters may also be scored from costs that hold it once (the same raw
costs); a parametrized repeat needs its own "<name>#<k>" entry.
optimaru.employee_scheduling._core ¶
Type stubs for optimaru.employee_scheduling._core — the employee-scheduling C++ solver.
The compiled module wraps the C++ employee-scheduling domain implementation in
optimaru/employee_scheduling/cpp; that implementation imports the generic
engine from core/optimaru. Times are integer minutes from
an arbitrary "day 0, 00:00" reference; a calendar day is
t // MINUTES_PER_DAY.
Score convention: hard counts constraint violations (0 == feasible), soft
is the optimization objective; both are maximized (less negative is better).
Cost plugin system¶
Two ways to define the cost function:
-
Built-in (hand-tuned):
Solver(cfg).solve(schedule)— the eight default constraints at weight 1, scored by a hand-written marginal-delta incremental calculator (the fastest path). -
Assembled (plugin): build a :class:
DecomposedCalculatorfrom constraint specs (optimaru.employee_scheduling.constraints, one class per constraint) or by name with per-constraintweight/level/exponentand domain parameters, thenSolver(cfg).solve(schedule, calc). Every built-in constraint carries its own incremental (marginal-delta) evaluation and precomputes lookup tables at reset, so any assembly — custom weights, level overrides, shapedexponent != 1included — searches incrementally out of the box, at ~0.9x the built-in step rate (effectively parity).
The defaults (level, weight, reward) live in the C++ components and are
reported by :func:constraint_info; the constraint factory accepts the 30 names of
CONSTRAINT_NAMES.
MINUTES_PER_DAY
module-attribute
¶
MINUTES_PER_DAY: int
1440 — minutes in a day; day index of a time t is t // MINUTES_PER_DAY.
CONSTRAINT_NAMES
module-attribute
¶
CONSTRAINT_NAMES: tuple[str, ...]
Every name the constraint factory accepts (:meth:DecomposedCalculator.add, the
spec classes), in factory order. Default level and weight 1 each (the eight
defaults first in :func:constraint_info):
"required_skill_cost"hard; 1 per assigned shift whose required skill the employee lacks. [default]"employee_unavailability_cost"hard; minutes of assigned shifts on the employee's unavailable days. [default]"shift_overlap_cost"hard; overlapping minutes between two shifts of the same employee. [default]"max_one_shift_per_day_cost"hard; 1 per pair of same-employee shifts starting on the same day. [default]"min_rest_cost"hard; shortfall minutes belowmin_gap_minutes(600) of rest between two same-employee shifts. [default]"undesired_day_cost"soft; minutes on the employee's undesired days (per_day: 1 per shift). [default]"desired_day_cost"soft REWARD (raw <= 0, never hard); minutes on the employee's desired days (per_day: 1 per shift). [default]"desired_shift_cost"soft REWARD (raw <= 0, never hard); 1 per assigned shift matching a desired (day, location)."shift_count_imbalance_cost"soft; load-balancing "unfairness" statistic over per-employee shift counts (global). [default]"max_consecutive_days_cost"hard; days beyondvaluein any run of consecutive worked days."min_consecutive_days_cost"soft; shortfall belowvalueof any run."max_consecutive_days_off_cost"soft; interior off runs beyondvalue."rest_after_consecutive_work_cost"hard; after >=work_daysworked days in a row, shortfall of the following rest gap belowrest_days(end-of-horizon runs excluded)."max_weekly_minutes_cost"hard; assigned minutes beyondminutesper calendar week (week_anchor)."min_weekly_minutes_cost"soft; shortfall belowminutesin every week (guaranteed hours;week_anchor)."min_weekly_rest_days_cost"hard; worked days beyond7 - valueper calendar week (>=valuerest days per week)."assignment_cost"soft; money:shift_costs[name][id]override, elsecost_per_hour/cost_per_shift."unassigned_shifts_cost"hard; 1 per shift left unassigned (global)."shift_count_gap_cost"soft; busiest-vs-least-busy gap beyondtolerance(global)."weekly_minutes_gap_cost"soft; per calendar week, busiest-vs-least-busy gap of assigned minutes beyondtolerance_minutes, in hours (global)."shift_coverage_cost"soft; per (day, location) group, count of assignees holdingworker_skilloutside [min_count,max_count] (global)."location_run_length_cost"soft; maximal runs of days atlocationoutside [min_run,max_run]."rest_after_location_run_cost"hard; worked days in therest_daysafter a run atlocation."location_run_gap_cost"soft; shortfall belowmin_gapdays between two runs atlocation."worker_location_count_cost"SOFT; per worker holdingworker_skill, count oflocationshifts outside [min_count,max_count]."day_pattern_cost"soft; 1 per window matchingpattern, a comma-separated list of locations,OFF(a day with no work),*(any day),WORK(any worked day) or!x(a worked day not at location x)."target_days_off_cost"soft; shortfall belowmin_countdays off amongtarget_days."worker_day_count_in_range_cost"SOFT; distinct worked days in [lo,hi] outside [min_count,max_count]."location_imbalance_cost"soft; fairness of a per-worker count across workers holdingworker_skill(global)."worker_pairing_cost"soft; 1 per (day, location) bucket where the pairing ofanchorandpairedfails (raw >= 0; global).
Unit constraints take an optional scope worker_indices / shift_indices;
shift_coverage_cost scopes natively; the other globals take none.
ConstraintSpec ¶
Bases: Protocol
Anything with the spec attributes: the Constraint dataclasses
(optimaru.employee_scheduling.constraints) and the pydantic constraint models
(optimaru.employee_scheduling.models) both qualify. params() (optional) returns the
domain parameters.
Score ¶
Two-level score (hard, soft). hard is an integer violation total (0 == feasible);
soft carries the objective, including fractional terms such as the
load-balancing unfairness. Compared lexicographically (hard first).
Employee ¶
Problem fact: a person with skills and per-day availability preferences.
Date sets contain day indices (see minutes / MINUTES_PER_DAY).
desired_shifts
instance-attribute
¶
desired_shifts: set[tuple[int, str]]
(day, location) location-specific work preferences (see the desired_shift_cost constraint).
Shift ¶
One shift to be assigned to one employee.
employee_index is the decision variable (-1 == unassigned); the solver
writes it.
start
instance-attribute
¶
start: int
Start time in minutes from day 0 (see minutes); solving and scoring
raise ValueError unless 0 <= start < end, with end at most about 100 years
(36525 days) from day 0.
required_skill
instance-attribute
¶
required_skill: str
Skill the assignee needs; "" = none. At most 64 distinct values across the shifts of a schedule, else solving and scoring raise ValueError.
employee_index
instance-attribute
¶
employee_index: int
Index into EmployeeSchedule.employees; -1 == unassigned. Solving and
scoring raise ValueError for a value outside that range.
pinned
instance-attribute
¶
pinned: bool
If True the shift keeps its employee_index fixed (never moved). The four per-shift constraints (required skill, unavailability, undesired and desired day) skip it; the constraints between shifts and the shift-count imbalance count it. Solving and scoring raise ValueError if it has none.
EmployeeSchedule ¶
The solution: employees (value range) + shifts (entities).
Solving mutates the shifts' employee_index and sets score in place.
ConstraintTotalDict ¶
DecomposedCalculator ¶
Plugin-style cost assembly: pick constraints, tune weights, override
hard/soft, shape superlinearly — then pass to
Solver.solve(schedule, calc) or score fixed assignments directly.
Assemble from constraint spec objects (optimaru.employee_scheduling.constraints)::
DecomposedCalculator([RequiredSkillCost(), MinRestCost(weight=0.25, level="soft")])
or incrementally by name via :meth:add. The eight defaults at their
default weights (see :func:default_calculator) reproduce
:func:calculate_score exactly. A constraint may be added several times
(other parameters, scope or knobs, or the same ones); each instance is
scored on its own with its own knobs, and the instances add up.
delta_group_count
property
¶
delta_group_count: int
Structural delta groups compiled by the last score/solve reset.
add ¶
add(name: str, weight: float | None = None, level: str | None = None, exponent: float = 1.0, *, offset: float = 0.0, clip: bool = True, **params: object) -> None
Add a built-in constraint (see CONSTRAINT_NAMES).
None = the component's default weight; otherwise a linear
multiplier (finite, >= 0) on the constraint's cost.
level: None keeps the constraint's default level, otherwise "hard"
or "soft", or a Level (e.g. add("undesired_day_cost",
level="hard") promotes it; add("min_rest_cost",
level="soft", weight=0.25) demotes it). The rewards
(desired_day_cost, desired_shift_cost) refuse "hard"; "medium"
is refused (no medium level here), and hard= raises
TypeError (the level is level=).
exponent: sign-preserving power shaping of the PER-EMPLOYEE cost:
contribution = weight * sign(c) * abs(c) ** exponent.
2.0 = squared, 3.0 = cubed — concentrated violations on one
employee become disproportionately expensive. Shaping is
applied on top of the incrementally maintained raw cost, so
it does not slow the search down.
offset: (keyword) shifts that shaping, any finite number (0.0 =
none). With clip=True (the default) only what lies
beyond it counts: sign(c) * max(0, abs(c) - offset) **
exponent; with clip=False the literal (c - offset)
** exponent (sign-preserving), which charges every
employee the constraint evaluates, a raw 0 included (a worker
scope evaluates its employees only), and rewards below the
offset; with an offset it is refused on hard (ValueError),
because hard 0 must mean no violation.
params: constraint-specific options such as
pattern="Location A,OFF,Location B" or value=6, and the
scope worker_indices / shift_indices.
The same checks as a spec pick: ValueError for an unknown name, a refused level or an invalid knob value, TypeError for a knob of the wrong type. Duplicates are allowed (each call is its own instance; their costs add up).
score ¶
score(schedule: EmployeeSchedule) -> Score
Score schedule's current assignment with this assembly (also
stores schedule.score) and prime the calculator so
:meth:constraint_totals explains the result.
constraint_totals ¶
constraint_totals() -> list[ConstraintTotalDict]
Weighted cost per constraint instance for the last scored/solved solution — the score explanation ("which constraint costs how much").
ConstraintInfo ¶
Bases: NamedTuple
One constraint-catalog row, read off the C++ default and catalog assemblies.
SolverConfig ¶
Termination, seeding and search options for Solver.
spent_limit_seconds
instance-attribute
¶
spent_limit_seconds: float
Wall-clock budget for solve() (default 30s).
no_improvement_limit_seconds
instance-attribute
¶
no_improvement_limit_seconds: float
Stop after this many seconds without a best-score improvement; 0 disables
it. Alias of unimproved_spent_limit_seconds.
unimproved_spent_limit_seconds
instance-attribute
¶
unimproved_spent_limit_seconds: float
Wall-clock time since last best-score improvement; 0 disables it.
step_count_limit
instance-attribute
¶
step_count_limit: int
Local-search step budget; 0 disables it.
no_improvement_step_count_limit
instance-attribute
¶
no_improvement_step_count_limit: int
Stop after this many steps without a best-score improvement; 0 disables
it. Alias of unimproved_step_count_limit.
unimproved_step_count_limit
instance-attribute
¶
unimproved_step_count_limit: int
Steps since last best-score improvement; 0 disables it.
random_seed
instance-attribute
¶
random_seed: int
Seed of the search; the same seed reproduces the same search (with several starts and a target that is reached, the start that reaches it first can differ between runs).
parallel_solver_count
instance-attribute
¶
parallel_solver_count: int
Independent parallel starts (seed + i each); the best final score wins. A start that
reaches best_score_limit stops the others. Ignored when a calculator is passed to
Solver.solve.
full_assert
instance-attribute
¶
full_assert: bool
Re-verify every incremental score against a full recompute after every move (a debugging aid; much slower).
guided_moves
instance-attribute
¶
guided_moves: bool
Violation/skill-guided move selection (default True). False = uniform random moves.
employee_greedy_construction
instance-attribute
¶
employee_greedy_construction: bool
Seed unassigned shifts with a day-aware greedy construction heuristic before local search (default True).
greedy_repair_budget_fraction
instance-attribute
¶
greedy_repair_budget_fraction: float
Share of the time budget reserved for the post-local-search greedy hard-repair; local search gets the rest, so total wall time honors the limit. Default 0.0 (off). Range [0, 0.9).
late_acceptance_size
instance-attribute
¶
late_acceptance_size: int
Late-acceptance queue length (default 400).
ruin_recreate
instance-attribute
¶
ruin_recreate: bool
Enable adaptive ruin-and-recreate kicks on stagnation.
ruin_recreate_unimproved_step_trigger
instance-attribute
¶
ruin_recreate_unimproved_step_trigger: int
Minimum unimproved steps before a ruin-and-recreate kick.
ruin_recreate_min_ruin_fraction
instance-attribute
¶
ruin_recreate_min_ruin_fraction: float
Minimum fraction of entities to ruin per kick.
ruin_recreate_max_ruin_fraction
instance-attribute
¶
ruin_recreate_max_ruin_fraction: float
Maximum fraction of entities to ruin per kick.
ruin_recreate_max_ruin_count
instance-attribute
¶
ruin_recreate_max_ruin_count: int
Absolute cap on entities ruined per kick.
ruin_recreate_operator_decay
instance-attribute
¶
ruin_recreate_operator_decay: float
Adaptive operator weight decay; higher adapts more slowly.
ruin_recreate_rewards
instance-attribute
¶
ruin_recreate_rewards: list[float]
Rewards for NEW_BEST, BETTER, ACCEPTED and REJECTED outcomes.
ruin_recreate_polish_steps
instance-attribute
¶
ruin_recreate_polish_steps: int
Hill-climbing small-move polish steps per ruin-and-recreate kick.
ruin_recreate_as_move_weight
instance-attribute
¶
ruin_recreate_as_move_weight: float
Probability that a step draws destroy-and-repair as an ordinary, acceptor-judged move rather than only as a stagnation kick. 0 disables it (the default for employee scheduling: measured, descent carries this domain and the two do not stack).
ruin_recreate_as_move_max_ruin
instance-attribute
¶
ruin_recreate_as_move_max_ruin: int
Ruin size for the as-a-move form; much smaller than a kick's.
descent_weight
instance-attribute
¶
descent_weight: float
Probability that a step draws best-improvement descent over one nearby entity pair — every value of each entity plus their swap, repeated until the pair is locally optimal. One sweep costs ~2x the value-range in score evaluations, so the usable weight scales with how many employees there are (default 0.02).
descent_max_sweeps
instance-attribute
¶
descent_max_sweeps: int
Give up on a pair after this many improving passes (default 4).
change_move_weight
instance-attribute
¶
change_move_weight: float
Assignment-shape change move relative weight; 0 disables it.
swap_move_weight
instance-attribute
¶
swap_move_weight: float
Assignment-shape swap move relative weight; 0 disables it.
nearby_shifts
instance-attribute
¶
nearby_shifts: bool
Temporal nearby selection (default True): bias swap partners, descent pairs and related-ruin clusters toward shifts whose start times are close, where the pairwise hard constraints (overlap, one-per-day, min-rest) actually interact. Neighbor-list size is auto-derived from the densest 24h start-time window of the instance.
nearby_shifts_probability
instance-attribute
¶
nearby_shifts_probability: float
Probability that a swap partner is drawn from the nearby list instead of uniformly (default 0.65; measured best compromise across instance sizes — prefer 0.8 for large-only workloads of ~1000+ shifts). Range [0, 1].
smart_change_moves
instance-attribute
¶
smart_change_moves: bool
Enable employee-scheduling smart change moves when guided_moves is True. The move samples several employees for one shift and keeps the best sampled reassignment as the local-search candidate.
smart_change_candidate_count
instance-attribute
¶
smart_change_candidate_count: int
Employees sampled per smart change move (default 6).
employee_day_repair_moves
instance-attribute
¶
employee_day_repair_moves: bool
Enable repair moves for one-shift-per-day violations when guided_moves is True. The move relocates one duplicate-day assignment to an off employee.
employee_run_repair_moves
instance-attribute
¶
employee_run_repair_moves: bool
Enable repair moves for overlong consecutive-work runs when guided_moves is True.
employee_run_repair_max_days
instance-attribute
¶
employee_run_repair_max_days: int
Worked-day run length that triggers run repair moves (default 3).
employee_window_moves
instance-attribute
¶
employee_window_moves: bool
Enable employee-scheduling window moves when guided_moves is True. The move swaps two employees' assignments over a short day window.
employee_window_max_days
instance-attribute
¶
employee_window_max_days: int
Maximum day-window length for employee window moves (default 3).
custom_move_probability
instance-attribute
¶
custom_move_probability: float
Maximum probability of consulting the adaptive custom-move pool per ordinary search step (default 0.30). This keeps expensive employee window moves from monopolizing the search after a recent reward.
employee_ruin_moves
instance-attribute
¶
employee_ruin_moves: bool
Enable employee-aware ruin sets for adaptive ruin-and-recreate when guided_moves and ruin_recreate are True.
employee_unassign_moves
instance-attribute
¶
employee_unassign_moves: bool
Enable the unassign move (default False): empties an over-staffed slot by setting an assignment back to unassigned, so coverage slots are optional rather than always filled.
relocate_move_weight
instance-attribute
¶
relocate_move_weight: float
Sequence-shape relocate move relative weight; unused by employee scheduling.
list_swap_move_weight
instance-attribute
¶
list_swap_move_weight: float
Sequence-shape swap move relative weight; unused by employee scheduling.
two_opt_move_weight
instance-attribute
¶
two_opt_move_weight: float
Sequence-shape 2-opt move relative weight; unused by employee scheduling.
or_opt_move_weight
instance-attribute
¶
or_opt_move_weight: float
Sequence-shape Or-opt move relative weight; unused by employee scheduling.
tail_swap_move_weight
instance-attribute
¶
tail_swap_move_weight: float
Sequence-shape 2-opt* tail-swap relative weight; unused by employee scheduling.
best_score_limit
instance-attribute
¶
best_score_limit: tuple[int, float]
Stop early once bestScore >= (hard, soft), compared lexicographically. (0, -inf) stops at the first feasible solution. Default: unreachable.
on_new_best
instance-attribute
¶
on_new_best: Callable[[int, Score], None] | None
Callback fired on every new best solution: on_new_best(step, score). Runs on the solving thread and re-acquires the GIL, which solve() releases.
Solver ¶
Local-search solver (late acceptance + guided moves + adaptive
ruin-and-recreate). Solves IN PLACE: writes shift.employee_index and
schedule.score.
solve ¶
solve(schedule: EmployeeSchedule, calculator: DecomposedCalculator = ...) -> None
Without calculator: the built-in default cost (fastest).
With calculator: search and final score use that assembly — custom
weights included; the search runs incrementally via each
constraint's marginal-delta evaluation.
minutes ¶
minutes(day: int, hour: int = 0, minute: int = 0) -> int
Minutes from day 0 00:00 — the time unit used by Shift.start/end.
calculate_score ¶
calculate_score(schedule: EmployeeSchedule) -> Score
Full recompute with the eight DEFAULT constraints at their default
weights (also stores schedule.score). For a custom assembly use
:meth:DecomposedCalculator.score instead.
default_calculator ¶
default_calculator() -> DecomposedCalculator
A DecomposedCalculator preloaded with the eight default constraints at their default weights — equivalent to the built-in score.
constraint_costs ¶
constraint_costs(schedule: EmployeeSchedule, constraints: Iterable[ConstraintSpec] | None = None) -> dict[str, dict[str, Any]]
Raw per-employee cost of every constraint instance, 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": [...]]}}.
constraints None = the eight defaults; otherwise the picks, built by
the same factory as :class:DecomposedCalculator (an empty list raises
ValueError). The key is the Python name, "<name>#<k>" for the k-th
instance of a name picked more than once; name is always the plain
name and label the instance's display text. A global constraint
reports its single total as a one-element list. A worker-scoped constraint
carries "units", the employee indices it evaluates (ascending, in
range, each once): the literal offset formula charges those and no
other. Feed the result to optimaru.employee_scheduling.constraints.score with the
same list to re-price it.
constraint_info ¶
constraint_info() -> list[ConstraintInfo]
The constraint catalog: one row per name the constraint factory accepts (30).
The eight defaults come first (default_enabled=True, in
get_constraints() order), then the opt-in constraints
(default_enabled=False; unit constraints before global ones). Every
default weight is 1; desired_day_cost / desired_shift_cost are
rewards (reward=True, level_flippable=False).