This utility creates a timetable for a small (or maybe even big, if you have computing resources to find the solution) school using Google OR-Tools. It reads a JSON configuration that lists subjects, teachers, students and available rooms, then searches for an arrangement of lessons with the smallest penalty score.
Positives
- Flexible data format that covers many real-life constraints
- Generates both machine readable JSON and an easy HTML timetable
- Includes analysis tables for teachers and students
IMPORTANT
- Preparing the configuration file takes time
- Tested only on relatively small data sets (up to 50 students); large schools may need fine-tuning
- Searching for the best schedule will take a long time. Pay attention to script output, when it stops changing - probably you found solution which is good enough.
The following steps assume absolutely no prior experience with the command line. For configuration format look below.
- Open the project page on GitHub and click Code → Download ZIP.
- Unpack the ZIP to a folder such as Downloads/schedule (macOS) or C:\Users\you\Downloads\schedule (Windows).
Download and install Python 3 from python.org. On Windows check Add Python to PATH during setup.
Open a terminal window:
- macOS: open Finder → Applications → Utilities → Terminal.
- Windows: press Win+R, type
cmdand press Enter.
Run the following command:
pip install ortoolsInside the project folder make a copy of config-example.json and name it schedule-config.json.
Editing on macOS
- Open Finder and locate
schedule-config.json. - Right click the file and choose Duplicate if you want an extra backup.
- Edit the file with TextEdit or the free Sublime Text.
- Save the file with ⌘S.
Editing on Windows
- Use File Explorer to open the project folder.
- Right click
schedule-config.jsonand choose Copy, then Paste to keep a spare copy. - Edit the file with Notepad, Notepad++ or Sublime Text.
- Use File → Save when done.
- Open Terminal or Command Prompt as described above.
- Move to the project directory:
- macOS example:
cd ~/Downloads/schedule - Windows example:
cd %USERPROFILE%\Downloads\schedule
- macOS example:
- Check you are in the right place by typing
pwdon macOS orcdon Windows. You should see the path to the folder withnewSchedule.py. - Start the program with the default file names:
python newSchedule.pyAdvanced users can provide three optional parameters: a config file, the JSON output file and the HTML timetable.
python newSchedule.py schedule-config.json schedule.json schedule.htmlSet "objective": "check" in the configuration to only verify that a schedule is possible.
THIS SEARCHES FOR ANY SOLUTION AND DOES NOT OPTIMISE PENALTIES. Use "total" or
"fair" to find the best timetable.
While the solver runs you will see lines similar to
#163 1280.39s best:487960 next:[208710,487950] graph_cst_lns (d=9.26e-01 s=10029 t=0.11 p=0.51 stall=181 h=stalling)
Press Ctrl+C to stop early; the best solution so far will be saved. The search is CPU intensive and may run for hours.
The configuration file is divided into several sections. Values are stored as [value, "description"] pairs. The settings, defaults and penalties blocks are required. The model block is optional and should only be changed if you understand the effects.
- objective –
"total"minimises the sum of all penalties;"fair"balances penalties between teachers and students;"check"only tests if any schedule is possible. (default"total") - teacherAsStudents – how many student opinions one teacher counts as when calculating penalties. (default 15)
- duplicatesPenalty – penalty applied when a teacher or student appears in more than one lesson in the same slot. If greater than zero duplicates are allowed. (default 0)
- teacherImportance – base weight for teachers. Higher values make teacher gaps more costly. (default 20)
- studentImportance – base weight for students. Increase to prioritise student convenience. (default 10)
- optimalSlot – preferred starting slot when a subject lacks its own.
0is the first lesson. (default 0) - teacherArriveEarly – if
true, teachers are present from the first slot even without a lesson. (defaultfalse) - studentArriveEarly – if
true, students arrive for slot0even when their first lesson is later. (defaulttrue) - permutations – allow subject classes to be arranged in any order. (default
true) - avoidConsecutive – discourage placing the same subject on neighbouring days. (default
true)
- gapTeacher – penalty for idle teacher slots. High values reduce teacher free time, low values allow it. (default 30)
- gapStudent – penalty for gaps in a student day. Raise to keep days compact. (default 100)
- unoptimalSlot – penalty for each slot away from a subject's preferred time. Bigger values keep lessons closer to their optimum. (default 1)
- consecutiveClass – penalty when the same subject appears on consecutive days. High numbers spread classes apart. (default 10)
- teacherLessonStreak – array of penalties based on consecutive lessons for teachers. The last value applies to any longer streak.
- studentLessonStreak – similar penalties for students based on consecutive lessons.
List the days of teaching and available lesson numbers:
{"name": "Monday", "slots": [0,1,2,3,4]}Rooms where classes may take place. Each entry defines a capacity and optional list of subjects allowed in that room:
"Room 101": {"capacity": 20, "allowedSubjects": ["Chemistry"]}Optional field printName overrides the key when shown in reports.
Describe each subject with its teachers and lesson structure.
teachers– teachers who can teach the subjectprimaryTeachers– teachers that must be presentrequiredTeachers– number of teachers needed for each lessonrequiredCabinets– number of rooms needed for each lesson. When more than one cabinet is selected the combined capacity of all chosen rooms must fit the class sizeoptimalSlot– preferred starting slotclasses– list of lesson lengths that must occur on separate daysallowPermutations– allow the lesson order to changeavoidConsecutive– try not to schedule on back-to-back dayscabinets– rooms where the lesson may take placeprintName– optional name to display in reports
Mapping of teacher names to optional settings.
importance– overrides the default teacher weightarriveEarly– whether the teacher is present from slot0allowedSlots– specific slots when the teacher can workforbiddenSlots– slots the teacher cannot workprintName– optional name used in reports
List of students with their subjects and optional settings.
group– number of students if this is a group entryimportance– overrides the default student weightarriveEarly– whether the student arrives from the first slotallowedSlots– specific slots when the student can attendforbiddenSlots– slots the student cannot attend
Optional fixed lessons specified as [day, slot, subject, room, teachers?, length?] to lock
classes to certain times. The teachers element may be omitted, null or an empty array
to let the solver pick the best available teachers. length is optional and must match one
of the subject's defined class lengths when provided.
maxTime– solving time limit in seconds (default three hours). A larger value can improve results but takes longerworkers– CPU cores to use. By default it uses available cores minus two, but not less than fourshowProgress–trueto print progress lines during the search (default)
- schedule.json – machine readable output for further processing
- schedule.html – open in a browser to inspect the timetable with colour coded penalties
- Added penalties for consecutive classes and lesson streaks
- Automatic worker detection and improved defaults
- Expanded documentation with step-by-step instructions
- Initial schedule generator with JSON configuration and HTML report
- Basic analysis tables for teachers and students