Introducing a new way to review your PRs.

Read the announcement

nusmodifications / nusmods

🏫 Official course planning platform for National University of Singapore.

View on GitHub

20 documents · Updated Nov 6, 2026

docs / timetable-optimisation

Timetable optimisation

Timetable optimisation helps a student turn module lesson choices and attendance preferences into a usable timetable. The page combines the current timetable with a server-side search service, then returns a shareable NUSMods timetable that respects fixed choices where possible and makes trade-offs visible.

Product role

The optimiser is a tool within the campus tools group. It complements the venue and transport tools by considering travel between physical classes, while the module prerequisite explorer helps students assess module choices before they build a timetable. The timetable experience remains the place where students inspect and edit the result. The service runs behind the wider serverless and external APIs boundary.

Timetable context

The /optimiser page works from the active semester and the modules already present in the timetable. It also reads the class selected for each lesson in the timetable so a student can keep known choices while the service plans the rest. References: website/…/Routes.tsx• L24-30, website/…/OptimiserContent.tsx• L39-79

Constraint controls

The form separates rules that limit possible choices from preferences that guide the choice of the best schedule:

ControlPurposeTreatment
Live lessonsMarks lesson types that need live attendanceUsed with free-day and lesson-hour limits
Pinned lessonsKeeps the class selected in the current timetableFixed choice that the remaining lessons must fit around
Free daysKeeps live lessons off selected weekdaysRequired constraint
Earliest start and latest endSets the allowed window for live lessonsRequired constraint
Lunch windowGives the search a preferred time for a one-hour breakPreference, not a promise
Maximum consecutive hoursGives the search a preferred limit for uninterrupted live studyPreference, not a promise

Lessons not marked live are treated as recorded lessons. They do not use live-attendance limits such as free days, travel, lunch gaps, or consecutive-hours scoring. The free-day control shows Saturday or Sunday only when the current lesson options include that day. References: website/…/OptimiserForm.tsx• L44-80, website/…/OptimiserFreeDaySelect.tsx• L16-68, website/…/OptimiserFreeDaySelect.test.tsx• L28-81

Conflict feedback

The page checks the current choices before it calls the service. It shows conflicts when a pinned class falls on a free day, falls outside the allowed hours, or clashes with another pinned class. The optimise action stays disabled when there are no lesson options or when one of these hard conflicts exists. The service repeats key checks at its boundary because the browser is not the only possible caller. References: website/…/OptimiserContent.tsx• L81-113, website/…/OptimiserContent.tsx• L195-202, website/…/api_test.go• L365-513

Optimisation flow

The flow transforms the current timetable into a request, searches module lesson classes, and turns the chosen classes back into links that the main timetable view can open.

This diagram shows how the student's current timetable becomes either a complete result or a useful partial result.

flowchart LR
    A[Current semester timetable] --> B[Optimiser form]
    B --> C[Constraint checks]
    C -->|valid request| D[POST optimiser API]
    D --> E[Module and venue data]
    E --> F[Candidate class search]
    F --> G[Assignments and day slots]
    G --> H[Shareable timetable links]
    H --> I[Optimised or partial timetable view]

Request assembly

When the student starts an optimisation, the browser sends the module codes, academic period, lesson attendance mode, pinned classes, free days, time limits, lunch window, and consecutive-hours preference as one JSON request. Lesson keys use the form MODULE|LessonType; pinned entries add the class number as MODULE|LessonType|ClassNo. Times cross the boundary as four-digit HHMM values. References: website/…/OptimiserContent.tsx• L135-163, website/…/models.go• L18-37

Candidate preparation

The API gets each selected module for the requested academic year and semester from the NUSMods module data service. It groups the available sessions into class choices, removes physical choices that violate free days or the live lesson window, and adds venue data so the search can account for movement between classes. Sunday is treated as the seventh timetable day, so it remains available unless the student selects it as a free day. References: website/…/README.md• L39-51, website/…/models.go• L114-140, website/…/modules_test.go• L9-53

The solver builds a schedule by choosing one class group for each lesson type. It rejects choices that overlap in time and week with an existing class. Among schedules that fit the hard rules, it favors a good lunch gap, short gaps between classes, manageable consecutive study time, and shorter travel between known venues. These are search priorities, so the result is a preferred schedule rather than a guarantee that every soft preference is met. References: website/…/README.md• L53-82, website/…/constants.go• L44-63, website/…/solver_test.go• L10-61

API boundary

The optimiser API is a server-side boundary between the browser's user choices and the module timetable data used to evaluate them. It accepts one POST request and returns either a timetable state or an HTTP error.

Request contract

The request contract has two kinds of input. Module and academic fields identify the data set. Preference fields describe the schedule the student wants. The boundary requires at least one module and parses all time fields before it starts the search.

Field groupData carried across the boundary
Module scopemodules, acadYear, acadSem
Attendance moderecordings as lesson keys not requiring live attendance
Fixed choicespinnedSlots as lesson key plus class number
Hard limitsfreeDays, earliestTime, latestTime
Soft preferenceslunchStart, lunchEnd, maxConsecutiveHours

The handler accepts CORS preflight requests and POST requests. Other methods are rejected. Invalid JSON, malformed times, empty module input, and invalid pin references are client errors rather than search results. References: website/…/README.md• L117-137, website/…/models.go• L39-97, website/…/api_test.go• L144-220

Response contract

A successful response contains the selected class for each lesson type, day-grouped lesson slots, a score, and two timetable links. shareableLink contains the lessons that the search scheduled. defaultShareableLink also fills lessons that could not be placed with fallback classes so the student can adjust them in the normal timetable view.

Response partMeaning
AssignmentsLesson key to selected class number
DaySlotsChosen lesson slots arranged by day
Score and distance fieldsSearch quality information
shareableLinkTimetable with optimised assignments
defaultShareableLinkTimetable with fallback assignments for missing lessons

The result always represents seven timetable days from Monday through Sunday. The browser uses the returned day slots to find lesson types that were not assigned. A complete result opens the optimised timetable directly. A partial result gives the student a choice between the optimised lessons only and all lessons with fallback placements. References: website/…/models.go• L108-140, website/…/solver_test.go• L45-61, website/…/OptimiserContent.tsx• L166-177

Partial schedules

The search can return a useful partial timetable when it cannot place every lesson without breaking a conflict. The UI names the missing lesson types and explains that the selected rules left no valid placement. This keeps the successful choices available while making the unresolved work explicit. References: website/…/OptimiserResults.tsx• L28-123, website/…/OptimiserContent.tsx• L166-177, website/…/api_test.go• L267-304

Timetable handoff

The optimiser does not replace the timetable editor. It hands class assignments back through standard NUSMods share links, so the student can inspect the result, keep it, or adjust it with the existing timetable tools.

The API converts lesson assignments into the timetable link format for the requested semester. It creates the optimised link first, then creates a second link after adding fallback classes for lessons that the search skipped. The result page opens these links in a new tab after a response arrives. References: website/…/nusmods_link.go• L11-58, website/…/OptimiserResults.tsx• L19-45, website/…/api_test.go• L223-265

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the browser request fields and the API request model aligned. A renamed lesson key or pin format can make valid timetable selections fail at the boundary.
  • Keep the lesson-type abbreviations used to build share links aligned with the timetable link format. A mismatch can produce links that open without the intended class choices.
  • Keep the meaning of recorded lessons aligned across the form, conflict checks, candidate filters, and score calculation. Changing one physical-attendance rule can silently change the result.
  • Keep weekday handling aligned across the form, day indexes, returned DaySlots, and returned DayDistance. A mismatch can hide weekend choices or place them under the wrong day.
  • Keep venue names and coordinates aligned with the module slot data. Missing or stale venue data changes the travel preference and can alter the chosen timetable.
  • Keep the response slot shape aligned with the browser's unassigned-lesson check. If lesson keys disappear from DaySlots, the UI can report a complete schedule as partial or the reverse.

Important failure modes

TriggerConsequenceGuard
The request has no modules or a time is not a valid HHMM valueThe API rejects the request with a client error before searchingThe form starts from timetable modules and sends controlled time values; preserve boundary validation
A pin uses a missing lesson type, missing class, module outside the request, or duplicate lesson keyThe API rejects the request because it cannot honor the fixed choiceBuild pins from the current timetable and remove stale pins when lesson options change
A pinned live class falls on a selected free day or outside the live lesson windowThe browser blocks optimisation and the API also rejects the pinShow the conflict and require the student to change the pin or constraint
Module data cannot be fetched or decodedThe API returns an error instead of a timetableTreat upstream module data as a required dependency and surface the API error state
No conflict-free class group can be found for a lessonThe response can contain a partial timetable and an unassigned lesson listOffer both the optimised-only link and the fallback all-lessons link
A venue has no usable coordinatesThe search applies a venue penalty instead of a travel distanceKeep venue data current and treat travel quality as a preference rather than a hard rule
Weekend day indexes are not kept at seven daysSunday classes can be omitted or appear under the wrong dayPreserve the Monday-to-Sunday order across candidate data, results, and UI controls

Key files

FileWhy to read it
website/…/OptimiserContent.tsxMain UI coordinator. It joins the current timetable, form state, conflict checks, API call, and result state.
website/…/OptimiserForm.tsxShows the user-facing constraint groups and separates required rules from preferences.
website/…/OptimiserFreeDaySelect.tsxShows only weekdays that can occur in the current lesson choices and lets the student mark them free.
website/…/optimiser.tsDefines the browser-side request and response boundary.
website/…/optimise.goDefines the HTTP entry point and error boundary.
website/…/models.goDefines the request, response, lesson key, timetable slot, and weekday contracts.
website/…/modules.goExplains how module sessions become candidate class choices under hard constraints.
website/…/solver.goExplains how candidate choices are combined and ranked.
website/…/nusmods_link.goExplains how assignments become standard NUSMods timetable links.
website/…/OptimiserResults.tsxShows how complete and partial results are presented to the student.
website/…/api_test.goShows the API guarantees for constraints, pins, errors, and shareable links.