Skip to content

optimaru.sports_league_scheduling

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

optimaru.sports_league_scheduling

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

Team/Round/Match/LeagueSchedule/Score/Solver/SolverConfig/ calculate_score/constraint_costs/constraint_info come from the compiled C++ core (_core). Match.round is the decision variable (-1 == unassigned; the value is a position in LeagueSchedule.rounds), and solve changes it and score in place::

import optimaru.sports_league_scheduling as sl

schedule = sl.generate_demo_data()
sl.solve(schedule, time_limit_seconds=10.0, random_seed=42,
         stop_at_first_feasible=True)
print(schedule.score, schedule.assignment())

Score, at the default weights: hard = -(team_conflict_cost + consecutive_home_matches_cost + consecutive_away_matches_cost + repeat_match_on_next_day_cost), soft = -(the five *_hop_cost travel terms in km + 1000 x workday_classic_matches_cost). constraint_costs(schedule) gives the raw cost of every constraint (the only per-constraint surface); constraint_info() lists every constraint with its default level and weight. Change a weight or a level through a constraint selection (see optimaru.sports_league_scheduling.constraints).

The pydantic mirror (for serialization) is in optimaru.sports_league_scheduling.models.

optimaru.sports_league_scheduling.models

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

Mirrors _core's Team/Round/Match/LeagueSchedule and SolverConfig 1:1. Use it to store or transfer the engine shape as-is (debug dumps, regression snapshots, ...)::

from optimaru.sports_league_scheduling.models import LeagueScheduleModel, SolveConfig

model = LeagueScheduleModel.from_core(schedule)   # engine -> pydantic
clone = LeagueScheduleModel.model_validate_json(model.model_dump_json())
schedule2 = clone.to_core()                       # pydantic -> engine

TeamModel

Bases: StrictModel

Problem fact: a team. A match's home/away reference positions in the team list.

RoundModel

Bases: StrictModel

A round, the value a match is assigned. index is the round number the constraints use (same day / next day / first / last checks), weekend_or_holiday feeds workday_classic_matches_cost.

MatchModel

Bases: StrictModel

One match. round is a position in the rounds list (-1 = unassigned).

LeagueScheduleModel

Bases: StrictModel

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

to_core

to_core() -> _core.LeagueSchedule

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

from_core classmethod

from_core(schedule: LeagueSchedule) -> LeagueScheduleModel

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

SolveConfig

Bases: SolveConfigBase

Serializable mirror of _core.SolverConfig (for solve(config=...)).

late_acceptance_size 0 is automatic: clamp(32 * matches, 400, 3200). A positive value is used as it is. Either way it is 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.

LeagueScheduleRequest

Bases: SolveRequest

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

with_initial_solution

with_initial_solution(problem, solution)

Return a copy of problem whose search starts from solution.

solution is what a solve returns (LeagueScheduleModel.from_core), or a plain dict of that shape (the JSON the API returned). Matches are matched by id. A match 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.

round is a position in rounds, not Round.index, so it is only valid for the same rounds in the same order: ValueError if solution lists different ones.

Raises ValueError naming the match for an unknown or repeated id and for a round outside -1..round_count - 1 (the engine does not range-check).

parameter_uses

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

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

sports_league_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: LeagueScheduleRequest, *, constraints=None) -> LeagueScheduleModel

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

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

The default path (sl.solve(schedule)) enables all ten 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.sports_league_scheduling as sl
from optimaru.sports_league_scheduling.constraints import (
    TeamConflictCost, WorkdayClassicMatchesCost, get_constraints,
)

sl.solve(schedule, constraints=get_constraints())          # the defaults as-is
sl.solve(schedule, constraints=[                           # picked
    TeamConflictCost(), WorkdayClassicMatchesCost(weight=10_000),
])

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. None = the component default (1 for every constraint but WorkdayClassicMatchesCost, whose default is 1000). sl.constraint_info() reports the defaults.
  • level None = the default level, otherwise Level.HARD or Level.SOFT (or the names "hard" and "soft"). This use case has no medium level: level="medium" raises ValueError.
  • exponent sign-preserving power shaping: weight * sign(c) * |c| ** exponent. 2.0 = squared, so concentrated violations grow much costlier. The three unit constraints (StartToAwayHopCost, AwayToEndHopCost, WorkdayClassicMatchesCost) shape the cost of each round; the seven global constraints shape their one total.
  • 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 round below the offset — an empty one (cost 0) included — lowers the penalty, and a global total below it does too. With an offset it is refused on hard (TeamConflictCost and the other three hard globals by default), because hard 0 must mean no violation.

The same constraint may be picked several times; each pick is scored on its own with its own knobs (its level included) and the picks add up. Every away-to-away kilometre costs 1, and the total beyond 1000 km costs 0.01 x its square on top::

sl.solve(schedule, constraints=[
    *get_constraints(),
    AwayToAwayHopCost(weight=0.01, exponent=2, offset=1000),
])

sl.constraint_costs(schedule, picks) keys the second pick "away_to_away_hop_cost#2".

The five travel terms (*_hop_cost) are all in km, so adding them up makes sense. The 1'000 of workday_classic_matches_cost is set against those km — expensive enough that the search takes long detours to put a derby on a Saturday.

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 sl.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 matches in the same round sharing at least one team. Default: hard, weight 1.

A pair sharing both teams (a fixture and its return) also counts once.

ConsecutiveHomeMatchesCost dataclass

Bases: Constraint

Teams playing at home four or more rounds in a row. Default: hard, weight 1.

The cost is the whole run length (a run of 4 costs 4, not the excess over 3). Several home matches in one round count once — what makes the run is the round being there at all.

ConsecutiveAwayMatchesCost dataclass

Bases: Constraint

The away mirror of consecutive_home_matches_cost. Default: hard, weight 1.

This is the one that actually keeps teams from living on the road for weeks.

RepeatMatchOnNextDayCost dataclass

Bases: Constraint

Matches whose return fixture is played in the very next round. Default: hard, weight 1.

At most 1 point per match however many return fixtures are there.

StartToAwayHopCost dataclass

Bases: Constraint

Km the away team travels from its home to a match in a round with no round index right before it (the season's first round, or the first round after a gap in the indices). Default: soft, weight 1.

HomeToAwayHopCost dataclass

Bases: Constraint

Km traveled by a team going away in the round after a home match. Default: soft, weight 1.

For pairs (m1 in round i, m2 in i+1) with m2.away == m1.home, dist(m1.home, m2.home) is charged.

AwayToAwayHopCost dataclass

Bases: Constraint

Km a team on two consecutive away rounds travels from one home ground to the next. Default: soft, weight 1.

AwayToHomeHopCost dataclass

Bases: Constraint

Km a team playing at home after an away round travels back. Default: soft, weight 1.

The distance is dist(m1.home, m1.away) of the earlier match — it depends only on m1, so the later match contributes the earlier match's distance, not its own.

AwayToEndHopCost dataclass

Bases: Constraint

Km the away team travels home after a match in a round with no round index right after it (the season's last round, or the last round before a gap in the indices). Default: soft, weight 1.

WorkdayClassicMatchesCost dataclass

Bases: Constraint

Derbies played in a round that is neither a weekend nor a holiday. Default: soft, weight 1000.

Expensive enough against the km travel terms that the search takes long detours to put a derby on a Saturday.

get_constraints

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

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

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

get_constraints([TeamConflictCost(), WorkdayClassicMatchesCost(weight=10_000)])

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 sl.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 = sl.constraint_costs(schedule)
score(raw)                     # default set
score(raw, [TeamConflictCost(), WorkdayClassicMatchesCost(weight=10_000)])
score(raw, [AwayToAwayHopCost(), AwayToAwayHopCost(exponent=2, offset=1000)])

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's applyRaw; rounding the total afterwards gives different values). weight=None / level=None read the entry's default weight and level. A second pick of a constraint reads the same raw costs with its own knobs.

When constraints is given, only those constraints are scored — the same semantics as get_constraints. Unknown names raise ValueError.

optimaru.sports_league_scheduling._core

Type stubs for optimaru.sports_league_scheduling._core — the sports-league-scheduling C++ solver.

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

Domain: assign a round (Round) to every match of the league (Match). Match.round is the decision variable and holds a position in the LeagueSchedule.rounds list (-1 == unassigned). Round adjacency (same day / next day / first / last) is all based on Round.index.

Score convention: hard is the number of constraint violations (0 == feasible), soft is minus the sum of travel distance (km) and classic penalties. Both are maximized.

Constraints (hard/soft), at the default weights (the C++ components' defaults, reported by constraint_info()): hard 1. team_conflict_cost -1 per pair of matches in the same round index sharing a team (once per pair even if both teams match) hard 2. consecutive_home_matches_cost when a team's home matches cover 4+ distinct consecutive round indices, -n for the run length (duplicate matches on one index count as 1) hard 3. consecutive_away_matches_cost the same for away matches hard 4. repeat_match_on_next_day_cost -1 per match whose return fixture is in the next round index (at most once per match) soft 5. start_to_away_hop_cost per match with no previous round index, -dist(away, home) soft 6. home_to_away_hop_cost for consecutive-index pairs (m1, m2) with m2.away == m1.home, -dist(m1.home, m2.home) soft 7. away_to_away_hop_cost if m2.away == m1.away, -dist(m1.home, m2.home) soft 8. away_to_home_hop_cost if m2.home == m1.away, -dist(m1.home, m1.away) soft 9. away_to_end_hop_cost per match with no next round index, -dist(home, away) soft 10. workday_classic_matches_cost per classic match in a non-weekend/holiday round -1000 (weight 1000)

Score

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

is_feasible

is_feasible() -> bool

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

Team

Problem fact: a team. Matches reference teams by position in the team list.

Round

A round, the value a match is assigned. index is the round number the constraints use (>= 0; usually consecutive 0..N-1, but sparse is fine).

Match

One match to get a round. round is the decision variable (-1 == unassigned; the value is a position in the rounds list), written by the solver.

LeagueSchedule

The problem and its solution: teams/rounds (value range) + matches + the distance matrix. solve changes the matches' round and score in place.

Note: list attributes such as matches return copies, so to change assignments use set_assignment or write them on the Matches before building the LeagueSchedule.

distance_to_team instance-attribute

distance_to_team: list[list[int]]

[from][to] km distance matrix (direction preserved). Empty list = all 0.

assignment

assignment() -> list[int]

Current round value per match (the solution vector).

set_assignment

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

Bulk-write the round per match. ValueError if the length differs from the match count.

SolverConfig

Termination conditions / seed / search options of Solver.

spent_limit_seconds instance-attribute

spent_limit_seconds: float

Wall-clock budget of solve() (default 30 s).

unimproved_spent_limit_seconds instance-attribute

unimproved_spent_limit_seconds: float

Time limit since the last new best; 0 disables.

step_count_limit instance-attribute

step_count_limit: int

Local-search step budget; 0 disables.

unimproved_step_count_limit instance-attribute

unimproved_step_count_limit: int

Step limit since the last new best; 0 disables.

parallel_solver_count instance-attribute

parallel_solver_count: int

Number of independent multistarts (seed+i); the best wins.

late_acceptance_size instance-attribute

late_acceptance_size: int

LA history length. 0 = automatic (clamp(32 * matches, 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.

full_assert instance-attribute

full_assert: bool

Re-checks incremental == full recompute on every move (for debugging, slow).

nearby_size instance-attribute

nearby_size: int

Number of nearby neighbors — matches sharing a team, ordered by home ground distance. 0 = automatic (4 * teams), negative disables nearby selection.

nearby_probability instance-attribute

nearby_probability: float

Probability of drawing the swap partner from the nearby neighbors.

costliest_match_sample instance-attribute

costliest_match_sample: int

Random sample size when picking a match to move — the one with the largest current travel penalty among them is chosen (tournament selection). 1 means uniform random. While infeasible it automatically falls back to uniform random.

best_score_limit instance-attribute

best_score_limit: tuple[int, float]

Stop early once bestScore >= (hard, soft). (0, -inf) stops at the first feasible.

on_new_best instance-attribute

on_new_best: Callable[[int, Score], None] | None

Called on every new best: on_new_best(step, score).

Solver

solve

solve(schedule: LeagueSchedule) -> None

Solves in place: writes matches[*].round and schedule.score.

solve_with_constraints

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

Score the same solve with a caller-chosen constraint set (see optimaru.sports_league_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, and the instances add up.

ConstraintInfo

Bases: NamedTuple

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

calculate_score

calculate_score(schedule: LeagueSchedule) -> Score

Full recompute of all 10 constraints (also stored in schedule.score).

list_constraints

list_constraints() -> list[str]

Constraint names scored by this domain (default assembly order, snake_case: the three unit constraints first, then the globals): start_to_away_hop_cost, away_to_end_hop_cost, workday_classic_matches_cost, team_conflict_cost, consecutive_home_matches_cost, consecutive_away_matches_cost, repeat_match_on_next_day_cost, home_to_away_hop_cost, away_to_away_hop_cost, away_to_home_hop_cost. The same names optimaru.sports_league_scheduling.constraints uses.

constraint_costs

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

Per-constraint raw costs — before weight/exponent/offset/level rounding: {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}}. The three unit constraints report one cost per round position, an empty round included, the seven globals a single total. 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. optimaru.sports_league_scheduling.constraints.score() takes these and produces a score. This is the only per-constraint surface.

constraint_info

constraint_info() -> list[ConstraintInfo]

The constraint catalog, in list_constraints() order: start_to_away_hop_cost, away_to_end_hop_cost (soft, 1), workday_classic_matches_cost (soft, 1000), team_conflict_cost, consecutive_home_matches_cost, consecutive_away_matches_cost, repeat_match_on_next_day_cost (hard, 1), home_to_away_hop_cost, away_to_away_hop_cost, away_to_home_hop_cost (soft, 1); all flippable, none a reward, all scored by default (default_enabled).