LZR league scheduler (2023-2025)
Side project for a weekend sports league - Python, OR-Tools (MIP), pandas, PyInstaller
A friend runs the LZR weekend leagues in Novi Sad. Every few days he needs a new round (kolo) of matches: who plays whom, on which court, at which kickoff time, across several leagues and a small set of halls. For years that meant hours in Excel. I turned the same workbook into a mixed-integer program that reads the sheet, respects the rules, and writes the next round back out.
This page is only about the scheduler - the workbook in, the next round out.
The problem
Each weekend, many teams across multiple leagues need games on a limited pool of court-time slots (Saturday and Sunday, overlapping kickoff times - a 10:10 start is not a clean hour boundary).
A legal round must satisfy all of this at once:
| Rule type | What it means |
|---|---|
| Hard - league | Two teams meet only if they are in the same league. |
| Hard - season | Most pairs play once per season; some leagues run a double round (every pair twice). |
| Hard - capacity | Each team plays at most one game per round; each court-time slot holds at most one game. |
| Hard - venues | A pair may use a hall only if both teams score it above zero on their court-wish sheet (0 = unacceptable). |
| Hard - history | Pairs that already met this season are blocked, rebuilt from older koloXX sheets (including typo-ridden team names). |
| Soft - wishes | Time wishes are scored 1 / 2 / 3 (can’t / meh / fine). Court wishes add on top. The solver maximizes the sum of chosen preferences. |
| Soft - fairness | Teams that already got good slots are slightly less attractive next time; teams that sat out get pulled forward (missed-round bonus). |
On the first full workbook I targeted, that was 143 teams in 6 leagues and 83 possible court-times, of which only the rows marked open for that weekend’s availability profile are in play. Doing it by hand is a combinatorial assignment problem. The right tool is not nested loops - it is OR.
The split that keeps the model sane: hard rules are constraints. Soft wishes are the objective. Mixing them is the usual way these models go wrong.
The model
Almost everything lives in two classes in schedule_lzr.py.
DataStorage - Excel as database and UI
The organizer’s .xlsx (or .ods) is both the input and the output. Required sheets include time wishes, court wishes, the master list of court-times with per-weekend open/closed columns, running statistics, optional historical koloXX rounds, and generated views.
From that the code builds:
- An upper-triangle legal-pairs matrix (starts at 1 or 2 for double-round leagues; decrements when a pair is scheduled).
- A 3D cost tensor
(team, team, timeslot): court score + time score, zeroed where a hall is ruled out, then adjusted for history (high rolling average = less attractive; missed games = bonus).
Overlapping clock times are not one column per kickoff. A JSON map (time_mapping.json) says which abstract preference columns each real day/time touches and with what weight.
ScheduleLZR - one round
- Keep only
(i, j, k)triples with non-zero cost. - Create binary variables
x[i,j,k]in OR-Tools (pywraplp, SCIP backend). - Constraints: each team in at most one chosen triple; each slot used at most once. (The “schedule every remaining pair this round” constraint is commented out - there are more pairings than courts, so a weekend is intentionally partial.)
- Maximize total cost of chosen games.
- Stop after 150 seconds; accept optimal or feasible.
- Write the round sheet, decrement legal pairs, update statistics, and optionally emit a per-team cross-round overview (
pregledVremena).
Chained weekends on the command line:
python schedule_lzr.py Input.xlsx 10 standard
python schedule_lzr.py Input.xlsx 10 standard,extra
Each listed availability column is one solve; the next round reads the file the previous round wrote.
Season in production
The repo is a timeline of snapshots, not one perfect “run the whole season” script.
| Phase | What happened |
|---|---|
| PoC 23/24 | EDA in pandas, class design on paper, first ODS solve - learned that scheduling is optimization, not nested for loops. |
| Oct 2024 redesign | New workbook schema, DataStorage / ScheduleLZR split, time_mapping.json for messy kickoffs, notebooks with %autoreload while the module holds truth. |
| Live kolo 4-5 | Real mid-season input; fuzzy team names (difflib.SequenceMatcher, threshold 0.8) because last year’s sheets had typos; first text post export for publishing. |
| Kolo 6-9 | Chained solves from last week’s output; track byes and missed games so later rounds can flag makeup pairings. |
| Kolo 10-15 | Disbanded teams skipped; hand-removed pairs the model must not reschedule; assert rosters match across sheets; crash if legal_pairs goes negative after reload. |
| Kolo 20 + new season | Continue old season or cold-start a new one; pregledVremena grid so every team sees every round’s slot at a glance. |
The habit that stuck: optimize the next weekend from last weekend’s file, not one heroic season solve that dies when availability changes.
Shipping to a non-programmer
The canonical Python tree is lzr-rasporedar/ (requirements.txt, README, .gitignore). Same solver logic is frozen for Windows in a separate build folder.
Three small programs, each with a PyInstaller spec:
| Tool | Job |
|---|---|
| Solver exe | Drop in workbook, pick round number and availability column, get the next kolo. |
| Text exporter | Turn a round sheet into a plain-text post grouped by venue (optional Saturday/Sunday dates). |
| Duplicate checker | Before publishing, compare the new round with every earlier kolo and print repeated pairings (same fuzzy name logic). |
Build recipe (on Windows - building under Wine broke on numpy internals):
pyinstaller --onefile --add-data "time_mapping.json;." schedule_lzr.py
Lesson: PyInstaller + scientific Python is a target-OS build, not a “compile anywhere” fantasy.
What I learned
- OR framing - constraints vs objective, partial weekends, time limits and feasible vs optimal.
- Incremental operations - each
*Run*folder is “copy last week’s xlsx, solve the next column, keep txt + xlsx.” - Dirty data explicitly - fuzzy names with logged substitutions, disbanded teams, roster asserts, fail loud on illegal history.
- Deliverable ≠ solver output - the organizer needs a readable post and a duplicate check, not a status code from SCIP.
- Same muscle as day jobs - this is the amateur-league cousin of the MIP/CP work I later did at meat plants (Volur): encode the rules once, let the solver search.
Still open
Honest gaps in the code as it stands:
povezanostEkipasheet is required on disk but not read by the solver yet (linked teams or “must not meet” rules still manual).- Statistics updates are duplicated between “apply new round” and “replay history” (left myself
FIXMEnotes). - Double-round league list and disbanded-team list are constants in the file, not workbook columns.
mockup_input.jsonsketched a cleaner schema; the loader still expects Excel.
If you schedule a rec league and something here would help - or I got a rule wrong - please tell me.