Skip to content

optimaru.tournament_scheduling

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

optimaru.tournament_scheduling

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

Assigns teams to daily match slots (TeamAssignment). Four constraints (2 hard + 1 medium + 1 soft; the three score levels are folded as soft = -(medium * MEDIUM_SCALE + raw soft), MEDIUM_SCALE == 1e6; for the details see the models/_core docs). constraint_info() lists each constraint's default level and weight (assignment_count_imbalance_cost is medium at weight 1, in medium units); constraint_costs(schedule) gives the raw per-constraint costs::

import optimaru.tournament_scheduling as ts
from optimaru.tournament_scheduling.models import generate_demo_data

schedule = generate_demo_data()  # the demo instance (7 teams, 18 days x 4 slots)
result = ts.solve(schedule, time_limit_seconds=5.0, random_seed=42)
print(result.score_hard, result.score_soft)

solve accepts both the pydantic mirror (models.TournamentScheduleModel) and _core objects (TournamentSchedule). The pydantic mirror (for serialization) is in optimaru.tournament_scheduling.models.

optimaru.tournament_scheduling.models

Pydantic v2 mirror of the engine domain — for JSON serialization/deserialization.

Mirrors _core's Team/Day/UnavailabilityPenalty/TeamAssignment/TournamentSchedule 1:1. Teams/days are referenced by list index (a team is identified by its teams index, a day by its days index).

Score mapping (hard / medium / soft -> engine Score): score_hard is the hard level as-is, score_soft is -(medium unfairness * 1e6 + soft unfairness) — folded with a 1e6 offset so medium (per-team assignment balance) always dominates soft (head-to-head balance)::

from optimaru.tournament_scheduling.models import TournamentScheduleModel, generate_demo_data

model = generate_demo_data()                 # the demo instance
clone = TournamentScheduleModel.model_validate_json(model.model_dump_json())
schedule = clone.to_core()                   # pydantic -> engine

TeamModel

Bases: StrictModel

A participating team, identified by its list index.

DayModel

Bases: StrictModel

A match day. date_index is informational (references use the days list index).

UnavailabilityPenaltyModel

Bases: StrictModel

Unavailability: one hard point when (team, day) has at least one assignment.

TeamAssignmentModel

Bases: StrictModel

One match slot of a day. team is the decision variable (None == unassigned); ids must be unique.

TournamentScheduleModel

Bases: StrictModel

Pydantic mirror of the schedule. score is a read-only result, kept as a separate field.

to_core

to_core() -> _core.TournamentSchedule

pydantic -> engine object (the score field is ignored; the engine recomputes it).

from_core classmethod

from_core(schedule: TournamentSchedule) -> TournamentScheduleModel

engine object -> pydantic (including the current assignment and score).

TournamentScheduleRequest

Bases: SolveRequest

The tournament schedule with the settings of one solve (see SolveRequest for those).

generate_demo_data

generate_demo_data() -> TournamentScheduleModel

The demo instance: 7 teams, 18 days x 4 slots = 72 assignments, 12 unavailable days drawn from a seeded random.Random (deterministic).

with_initial_solution

with_initial_solution(problem, solution)

Return a copy of problem whose search starts from solution.

solution is what a solve returns: a TournamentScheduleModel, or a plain dict of that shape (the JSON the API returned). Assignments are matched by id. An assignment left out becomes unassigned and the construction heuristic places it, and only it, so a complete solution starts the search exactly from it. problem is not mutated. Pinned assignments keep their team on problem, whatever solution says.

team is a position in teams, so it is only valid for the same teams in the same order: ValueError if solution lists different ones.

Raises ValueError naming the assignment for an unknown or repeated id and for a team outside 0..team_count - 1 (None is unassigned; the engine does not range-check).

parameter_uses

parameter_uses(schedule: TournamentScheduleModel) -> list[ParameterUse]

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

tournament_scheduling.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: TournamentScheduleRequest, *, constraints=None) -> TournamentScheduleModel

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.tournament_scheduling.constraints

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

The default path (ts.solve(schedule)) enables all four 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(schedule, constraints=...).

A constraint list reads one way: one class call per constraint::

import optimaru.tournament_scheduling as ts
from optimaru.tournament_scheduling.constraints import (
    ConfrontationCountImbalanceCost, TeamConflictCost, TeamUnavailabilityCost,
    get_constraints,
)

ts.solve(schedule, constraints=get_constraints())           # the defaults as-is
ts.solve(schedule, constraints=[                             # picked
    TeamConflictCost(), TeamUnavailabilityCost(), ConfrontationCountImbalanceCost(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: team_conflict_cost is TeamConflictCost(), and so on.)

Every spec takes five knobs:

  • weight linear multiplier on the constraint cost, in units of its level. None = the C++ component default (ts.constraint_info() lists them; every default is 1).
  • level None = the default level, otherwise a Level or its name (Level.MEDIUM or "medium"). Any flippable constraint may take any of the three levels. AssignmentCountImbalanceCost is medium by default: folded into the engine's soft level as medium * 1e6 (MEDIUM_SCALE), like any constraint moved onto medium. On another level, level="hard" charges one hard unit per raw unit (the global total, rounded), level="soft" one soft unit per raw unit, and a weight is in units of the level in effect.
  • exponent sign-preserving power shaping: weight * sign(c) * |c| ** exponent, per team for the two hard constraints and on the total for the two imbalance constraints. 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; False shapes c - offset as it is, so a unit below the offset lowers the penalty. The literal form charges every unit the constraint evaluates, a raw 0 included: every team for TeamConflictCost, only the teams with an unavailability fact for TeamUnavailabilityCost (its constraint_costs() entry lists them as "units"), and the one total for an imbalance. With an offset it is refused on hard (TeamConflictCost and TeamUnavailabilityCost by 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. The head-to-head imbalance, plus its square beyond 2::

ts.solve(schedule, constraints=[
    *get_constraints(),
    ConfrontationCountImbalanceCost(exponent=2, offset=2),
])

ts.constraint_costs(schedule, picks) keys the second pick "confrontation_count_imbalance_cost#2".

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

TeamConflictCost dataclass

Bases: Constraint

Pairs of assignments one team has on the same day (C(c, 2) per team-day cell). Default: hard, weight 1.

TeamUnavailabilityCost dataclass

Bases: Constraint

(team, day) unavailability facts with at least one assignment on them. Default: hard, weight 1.

Counted per fact, not per assignment — two facts in one cell give 2, three assignments on one fact still give 1.

AssignmentCountImbalanceCost dataclass

Bases: Constraint

LoadBalance unfairness of assignment counts per team. Default: medium, weight 1.

Only teams that actually have assignments enter the balance (a team without assignments is not counted as load 0). The statistic crosses units, so this is a global constraint. The weight is in medium units; the domain folds the medium level into the engine soft level as medium * 1e6.

ConfrontationCountImbalanceCost dataclass

Bases: Constraint

LoadBalance unfairness of head-to-head counts per team pair. Default: soft, weight 1.

Each pair of same-day assignments of two different teams counts as one head-to-head (a team is not paired with itself), and only pairs with at least one head-to-head enter the balance. The statistic is over team pairs, so it is a global constraint no unit owns.

get_constraints

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

Return the cost function. Without arguments, all four default constraints.

When constraints is given, that list is used as-is — only the listed constraints are scored::

get_constraints([TeamConflictCost(), ConfrontationCountImbalanceCost(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 ts.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 = ts.constraint_costs(schedule)
score(raw)                     # default set
score(raw, [TeamConflictCost(), ConfrontationCountImbalanceCost(weight=10)])
score(raw, [TeamConflictCost(), TeamConflictCost(exponent=2, offset=1)])

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) and hard contributions are rounded per unit before summing (the same order as the engine's applyRaw; rounding the total afterwards gives different values).

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 same as schedule.score: the medium level (assignment_count_imbalance_cost) is folded into soft as medium * 1e6, the medium_fold every entry of costs carries.

optimaru.tournament_scheduling._core

Type stubs for optimaru.tournament_scheduling._core — the tournament-scheduling C++ solver.

The compiled module wraps the C++ domain in optimaru/tournament_scheduling/cpp, which imports the generic engine in core/optimaru.

Constraints (hard / medium / soft levels) and the score mapping (registry names; default weights per raw unit, all 1): hard 1. team_conflict_cost -1 per pair of same-team assignments on one day hard 2. team_unavailability_cost -1 when a (team, day) unavailability fact has an assignment med 3. assignment_count_imbalance_cost LoadBalance unfairness of assignment counts per team (-1 medium per raw unit) soft 4. confrontation_count_imbalance_cost LoadBalance unfairness of head-to-head counts per team pair

The engine score is Score(hard int, soft float), so medium is folded into soft: soft = -(medium unfairness * MEDIUM_SCALE + soft unfairness) (MEDIUM_SCALE == 1e6; medium always dominates soft). "Unfairness" is load-balance unfairness — sqrt(sum(load^2) - sum(load)^2 / n) rounded to 6 significant digits (HALF_EVEN).

Score

Two-level score (hard, soft). hard is the integer violation sum (0 == feasible); soft is the folded medium/soft objective. Lexicographic comparison (hard first).

is_feasible

is_feasible() -> bool

True when hard >= 0: no hard constraint is violated.

Team

Problem fact: a participating team. Its list index is the value assigned to TeamAssignment.team.

Day

Problem fact: a match day. Assignments/unavailability reference it by days index.

UnavailabilityPenalty

Problem fact: (team, day) unavailable — one hard point of team_unavailability_cost when the cell has at least one assignment (one point per fact, however many assignments the cell holds).

TeamAssignment

One match slot of a day. team is the decision variable (-1 == unassigned), written by the solver. ids must be unique.

team instance-attribute

team: int

Index into the teams list; -1 == unassigned.

pinned instance-attribute

pinned: bool

If True, team is fixed (it counts in the score but never moves).

TournamentSchedule

The problem and its solution: teams (the values) + days + unavailability + assignments. solve changes the team_assignments' team and score in place.

Note: list attributes such as team_assignments return copies, so use set_assignment to change assignments.

assignment

assignment() -> list[int]

Current team index per assignment (-1 == unassigned).

set_assignment

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

Bulk-write the team of every assignment (length must equal the number of assignments).

SolverConfig

Engine settings. Default: 30 s budget, LA + ALNS, single start.

late_acceptance_size instance-attribute

late_acceptance_size: int

0 = automatic: clamp(8 * assignments, 400, 3200).

descent_weight instance-attribute

descent_weight: float

Probability that a step runs a best-improvement descent over a nearby entity pair instead of the move mix (one sweep ≈ 2 * teams evaluations). Default 0 = off.

ruin_recreate_as_move_weight instance-attribute

ruin_recreate_as_move_weight: float

Weight of destroy-repair as an ordinary move judged by the acceptor (separate from the stagnation kick). Default 0 = off.

custom_move_probability instance-attribute

custom_move_probability: float

Upper bound on the probability of drawing the custom operator (TeamCountMove) in a step. 1 = unlimited.

value_recommender instance-attribute

value_recommender: bool

Steers the value choice of change moves to hard-feasible teams (no match that day + not unavailable), with or without constraints=. Default False.

team_count_moves instance-attribute

team_count_moves: bool

Macro moves on the number of loaded teams (empty / revive a team), with or without constraints=. The only path across the medium-level team-count barrier, so default True.

best_score_limit instance-attribute

best_score_limit: tuple[int, float]

Stop early at or above this score. E.g. (0, -inf) == stop at the first feasible.

Solver

solve

solve(schedule: TournamentSchedule) -> None

Solves in place: writes team_assignments[*].team and schedule.score. Pinned assignments are kept.

solve_with_constraints

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

Score the same solve with a caller-chosen constraint set (see optimaru.tournament_scheduling.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 on medium is folded into schedule.score.soft at MEDIUM_SCALE.

ConstraintInfo

Bases: NamedTuple

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

calculate_score

calculate_score(schedule: TournamentSchedule) -> Score

Full recalculation (also stored in schedule.score).

unfairness

unfairness(loads: Sequence[int]) -> float

Load-balance unfairness (6 significant digits, HALF_EVEN).

list_constraints

list_constraints() -> list[str]

Constraint names scored by this domain (default assembly order, snake_case: the two per-team constraints, then the two imbalance constraints). The same names optimaru.tournament_scheduling.constraints uses.

constraint_costs

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

Per-constraint, per-unit raw costs — before weight/exponent/offset/level rounding. A unit is a team; the two imbalance (global) constraints report one cost. optimaru.tournament_scheduling.constraints.score() takes these and produces a score: {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": "into_soft", "unit": 1e6}}}. The scoped team_unavailability_cost also carries "units": the teams with an unavailability fact, the only ones it evaluates (a literal offset, clip=False, charges those and no other team). None = the default constraints; a pick list (as for solve) scores exactly those picks, each entry carrying its pick's knobs, the k-th pick of a name keyed "#" from the second on. The medium fold belongs to the domain, so EVERY entry carries it.

constraint_info

constraint_info() -> list[ConstraintInfo]

The constraint catalog, in list_constraints() order: the default level and weight of each constraint (team_conflict_cost and team_unavailability_cost hard, assignment_count_imbalance_cost medium in medium units, confrontation_count_imbalance_cost soft; every default weight 1). All flippable, none a reward, all enabled by default.