Skip to content

●  How to use · Timetabling

Tournament scheduling

Spread teams over tournament days so that load stays balanced and every team gets a fair schedule.

What it decides

For every match slot of every day, the solver picks a team.

Minimal example

from optimaru import tournament_scheduling as ts
from optimaru.tournament_scheduling.models import (
    DayModel, TeamAssignmentModel, TeamModel, TournamentScheduleModel, UnavailabilityPenaltyModel,
)

problem = TournamentScheduleModel(
    teams=[TeamModel(name=name) for name in ["Reds", "Blues", "Greens", "Golds"]],
    days=[DayModel(date_index=day) for day in range(4)],
    unavailability_penalties=[UnavailabilityPenaltyModel(team=0, day=1)],
    team_assignments=[
        TeamAssignmentModel(id=day * 2 + slot, day=day, index_in_day=slot)
        for day in range(4) for slot in range(2)
    ],
)

result = ts.solve(problem, time_limit_seconds=2.0, random_seed=42)
print(result.score_hard, result.score_soft)
print([(a.day, a.index_in_day, a.team) for a in result.team_assignments])

The same use case as a Jupyter notebook, with charts and saved outputs: examples/tournament-scheduling.ipynb ↗

Input parameters

TeamModel

Field Meaning
name required Team name. Teams are referred to by position in teams.

DayModel

Field Meaning
date_index required Day number, for your own reference. Days are referred to by position in days.

UnavailabilityPenaltyModel

Field Meaning
team required Position of the team in teams. day required Position of the day in days.

TeamAssignmentModel

Field Meaning
id required Slot id. Ids must be unique. day required Position of the day in days. index_in_day Slot number within the day. pinned Keep the slot's team.

TournamentScheduleModel

Field Meaning
teams required Teams. days required Days. unavailability_penalties Days a team cannot play. team_assignments One entry per match slot.

Solve parameters

What you pass to the solve call. Time limit, seed and parallel count are here.

Parameter Default Meaning
time_limit_seconds None Search budget in seconds, from 0 to 1e9. Left unset, it is the config's spent_limit_seconds, 30 by default.
random_seed None Seed for the search. Left unset, it is the config's value, 0 by default.
parallel_solver_count None Independent parallel starts. Each gets its own seed and the full budget, and the best result wins. Left unset, it is the config's value, 1 by default.
stop_at_first_feasible False Stop as soon as hard 0 is reached.
on_new_best None Callback run on each new best solution. If it raises, the solve stops and raises the same exception.
config None A SolverConfig as the base configuration. Keyword arguments here override it for this solve only; the object you pass is not changed.
constraints None Which constraints to score, and how. Left unset, the defaults apply.
All search options (26)

Set these on a SolverConfig and pass it as config=.

Parameter Default Meaning
best_score_limit — Stop early once the best score reaches this value. By default it never fires.
change_move_weight 0.75 Relative share of change moves. 0 disables them.
custom_move_probability 1.0 Cap on how often a step may draw a use-case move. 1 means no cap.
descent_weight 0.0 Share of best-improvement descent. 0 turns it off.
full_assert False Check every incremental score against a full recompute. Slow; for debugging.
late_acceptance_size 0 Late-acceptance history length. 0 picks it from the instance size.
on_new_best None Callback run on each new best solution. If it raises, the solve stops and raises the same exception.
parallel_solver_count 1 Independent parallel starts, each with its own seed and the full budget. The best one wins.
random_seed 0 Seed for the search.
ruin_recreate True Run adaptive ruin-and-recreate kicks when the search stagnates.
ruin_recreate_as_move_max_ruin 12 Most entities that small ruin removes.
ruin_recreate_as_move_weight 0.0 Probability that a step is a small ruin and repair, judged like any other move. Negative picks it automatically where the use case supports that; 0 turns it off.
ruin_recreate_max_ruin_count 60 Absolute cap on entities removed per kick.
ruin_recreate_max_ruin_fraction 0.3 Largest share of the solution one kick removes.
ruin_recreate_min_ruin_fraction 0.1 Smallest share of the solution one kick removes.
ruin_recreate_operator_decay 0.8 How fast operator weights adapt.
ruin_recreate_polish_steps 5000 Hill-climbing moves that polish each kick. Not counted against step_count_limit.
ruin_recreate_rewards [33.0, 9.0, 3.0, 0.0] Operator rewards for a new best, a better, an accepted and a rejected result.
ruin_recreate_unimproved_step_trigger 5000 Steps without a new best before a kick.
spent_limit_seconds 30.0 Time budget in seconds, from 0 to 1e9.
step_count_limit 0 Stop after this many steps. 0 means no limit.
swap_move_weight 0.25 Relative share of swap moves. 0 disables them.
team_count_moves True Enable moves that change how many teams carry assignments.
unimproved_spent_limit_seconds 0.0 Stop after this many seconds without a new best. 0 means no limit.
unimproved_step_count_limit 0 Stop after this many steps without a new best. 0 means no limit.
value_recommender False Steer change moves toward teams that keep the move hard-feasible.

What comes back

solve takes the model and returns the solved model.

TeamAssignmentModel

Field Meaning
team Position in teams of the chosen team. None means unassigned.

TournamentScheduleModel

Field Meaning
score_hard Hard score. 0 means feasible. score_soft Medium and soft folded together, as -(medium * 1e6 + soft).

Constraints

Pick them by calling their classes from optimaru.tournament_scheduling.constraints, such as TeamConflictCost(). Only what you pass is scored; pass nothing to keep the defaults. A list may name a constraint more than once, and each pick is scored on its own. Each one takes these parameters:

Parameter Default Meaning
weight None Multiplier on the constraint's cost, in units of the level in effect. Left unset, the default weight below applies. A constraint whose default weight is 0 is off until you give it a weight.
level None "hard", "medium" or "soft" moves the constraint onto that level, as do Level.HARD, Level.MEDIUM and Level.SOFT. Left unset, it keeps the level below. This use case has a medium level, and any constraint may move onto it.
exponent 1.0 Sign-preserving power on the cost, above 0, taken after offset. 2.0 squares it, so concentrated violations cost much more. It applies per unit, such as a vehicle or a day, or to the total of a constraint scored as one sum.
offset 0.0 Subtracted from the cost x before the exponent, per unit or total like the exponent. It is in the cost's own measure: seconds, minutes, a count and so on. Any finite number of either sign, keyword only. clip decides what happens below it.
clip True True makes offset a threshold: only the part beyond it counts, max(0, x - offset) ** exponent, so a cost at or below it adds nothing. False takes the literal (x - offset) ** exponent, sign kept: a unit below the offset counts negative, as a reward, even one whose cost is 0. On a level that counts toward hard, clip=False with a non-zero offset raises ValueError, since hard 0 must mean no violation. Keyword only.

A medium constraint weighs 1 in medium units by default. The search compares solutions on medium * 1e6 + soft, so medium outranks soft while the soft total stays below 1e6. With level, any constraint moves onto any of the three levels: level="medium" puts it on medium, and "hard" or "soft" takes a medium one off it. A weight counts in units of the level in effect.

This continues the minimal example above.

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

picked = get_constraints([
    TeamConflictCost(), TeamUnavailabilityCost(), ConfrontationCountImbalanceCost(exponent=2.0),
])
custom = ts.solve(problem, time_limit_seconds=2.0, random_seed=42, constraints=picked)
print(custom.score_hard, custom.score_soft)
Name Level Default weight What it does
team_conflict_cost Hard 1 Pairs of assignments one team has on the same day.
team_unavailability_cost Hard 1 An unavailable team and day with at least one assignment, counted per entry.
assignment_count_imbalance_cost Medium 1 Unfairness of assignment counts per team.
confrontation_count_imbalance_cost Soft 1 Unfairness of head-to-head counts per team pair.

How constraints work →

Starting from an existing solution

This needs the latest release: pip install -U optimaru.

with_initial_solution(problem, solution) returns a copy of problem whose search starts from solution, the model a solve returned or that model as a JSON dict.

This continues the minimal example above.

seeded = ts.with_initial_solution(problem, result.model_dump(mode="json"))
again = ts.solve(seeded, time_limit_seconds=2.0, random_seed=43)
print(again.score_hard, again.score_soft)
  • Assignments are matched by id.
  • A complete solution skips construction: the search starts exactly from it. A partial one keeps what it gives, and only the assignments it leaves out are constructed.
  • With time_limit_seconds=0 the solve stops at once, so a complete solution comes back as it went in. Use the time limit for this: step_count_limit = 0 means no limit.
  • Pinned assignments keep their team on problem, whatever the solution says.
  • team is a position in teams, so a solution that lists different teams, or the same ones in another order, raises ValueError. So do unknown ids and out-of-range values.

Exceptions and limits

  • Only teams with at least one assignment count toward fairness, so the best score can leave a team with no matches. If every team must play, add that rule yourself.
  • score_soft folds medium into soft with a 1e6 offset.