Overview
The lottery controller uses a weighted random selection algorithm to assign students to classes. It processes priority registrations first, then interested registrations, while enforcing constraints like grade requirements, lunch periods, and class capacity.Core Components
LotteryAssignmentController
The main controller for computing lottery assignments. Location:esp/esp/program/controllers/lottery.py
Initialization
| Option | Default | Description |
|---|---|---|
Kp | 1.2 | Weight factor for priority students |
Ki | 1.1 | Weight factor for interested students |
check_grade | True | Validate grade constraints |
use_student_apps | False | Use student application ranks |
fill_low_priorities | False | Auto-fill priorities from interested classes |
max_timeslots | 0 | Max timeslots per student (0 = unlimited) |
max_sections | 0 | Max sections per student (0 = unlimited) |
stats_display | False | Show detailed logging |
directory | $HOME | Directory for output files |
Key Methods
compute_assignments(check_result=True)
Runs the lottery algorithm to assign students to classes.
- Process priority levels from highest to lowest
- Within each level, randomize section order by duration (longest first)
- Fill each section with eligible students using weighted random selection
- Process interested (non-priority) students after all priorities
- Optional: repeat for different student application ranks
compute_stats(display=True)
Generates statistics about lottery results.
num_lottery_students: Total students in lotterynum_enrolled_students: Students enrolled in at least 1 classnum_registrations: Total enrollments creatednum_sections: Available sectionsnum_full_classes: Sections filled to capacityoverall_priority_ratio: Fraction of priority requests fulfilledoverall_interest_ratio: Fraction of interested requests fulfilledoverall_utility: Weighted average student utility scorestudents_by_screwedness: List of (screwedness_score, student_id)hist_priority: Histogram of (assigned, requested) pairshist_interest: Histogram of interested class assignmentshist_timeslots_filled: Distribution of timeslots per student
save_assignments(try_mailman=True)
Saves computed assignments to the database.
- Clears previous enrollments (expires them with
end_date) - Creates
StudentRegistrationobjects with relationshipEnrolled - Updates mailman mailing lists (if configured)
clear_saved_assignments(delete=False)
Removes previous lottery results.
export_assignments() and import_assignments(data)
Save and restore lottery results.
get_computed_schedule(student_id, mode='assigned')
Retrieves a student’s schedule.
generate_screwed_csv(directory=None, n=None, stats=None)
Exports list of students with poor lottery outcomes.
Data Model
The lottery uses NumPy arrays for efficient computation.Core Arrays
Student Preferences:Assignment Algorithm
fill_section(si, priority=False, rank=10)
Assigns students to a single section.
Location: esp/esp/program/controllers/lottery.py:343
Algorithm:
- Calculate available spaces (section capacity, program capacity)
- Get students who signed up for this section (priority or interested)
- Filter by constraints:
- Grade requirements (unless grade range exception)
- Application rank (if using student apps)
- Max sections enrolled
- Max timeslots used
- Available in all section timeslots
- Not in different section of same class
- Lunch constraint (at least one free lunch period)
- If more students than spaces:
- Use weighted random selection based on
student_weights - Students who got more classes have lower weights
- Use weighted random selection based on
- Update student schedules and enrollments
- Update student weights: divide by
Kp(priority) orKi(interested)
True if section filled to capacity
Priority Levels
Priority registrations are stored asStudentRegistration with relationship names like Priority/1, Priority/2, etc.
Priority limit: Retrieved from program.priorityLimit()
Grade range exceptions: If enabled, adds an extra “priority level” that ignores grade requirements. Stored as relationship GradeRangeException.
Constraints
Grade Requirements
Sections havegrade_min and grade_max. Students must be in range unless:
check_gradeoption is False- Student has a grade range exception for that section
Lunch Constraint
If a section overlaps with a lunch period, students must have at least one other lunch period free. Lunch detection: Sections in the “Lunch” category.Scheduling Conflicts
Students cannot:- Be enrolled in two sections at the same time
- Be enrolled in multiple sections of the same class
Capacity Limits
Sections have hard capacity limits. Program may also have aprogram_size_max limiting total enrollment.
Weighting System
Each student starts with weight 1.0. After each assignment:- Priority assignment: weight ÷=
Kp(default 1.2) - Interested assignment: weight ÷=
Ki(default 1.1)
Utility Calculation
Student utility measures satisfaction:Lottery Modules
LotteryStudentRegModule
Student-facing registration interface. Location:esp/esp/program/modules/handlers/lotterystudentregmodule.py
Module Properties
Key Methods
lotterystudentreg(request, ...)
Main student registration page. Uses AJAX for dynamic content.
Template selection:
- HSSP-style:
student_reg_hssp.html(multi-level priorities) - Splash-style:
student_reg_splash.html(single priority level)
program.studentclassregmoduleinfo.use_priority and priority_limit.
timeslots_json(request, ...)
Returns program timeslots as JSON.
viewlotteryprefs(request, ...)
Displays student’s current lottery preferences.
Deadline: Requires /Classes/Lottery/View permission
students(QObject=False)
Returns students who entered the lottery.
LotteryFrontendModule
Admin interface for running the lottery. Location:esp/esp/program/modules/handlers/lotteryfrontendmodule.py
Module Properties
Key Methods
lottery(request, ...)
Main lottery control page.
Template: lottery.html
Context:
lottery_execute(request, ...)
AJAX endpoint to run the lottery.
Request: POST with lottery_* parameters
Response: JSON
lottery_save(request, ...)
AJAX endpoint to save lottery results.
Request: POST with lottery_data field (from lottery_execute)
Response: JSON
Exception Handling
The lottery defines custom exceptions:Usage Example
Two-Phase Registration
Some programs use a two-phase system: Phase 1: Star students - mark classes as starredPhase 2: Priority students - rank classes by priority The controller detects this:
Mailman Integration
Ifsettings.USE_MAILMAN is True, the lottery automatically updates mailing lists:
- Program list:
{program_type}_{program_instance}-students - Section lists:
{emailcode}-students - Class lists:
{class_emailcode}-students
Performance Considerations
- The lottery loads all students, sections, and timeslots into memory as NumPy arrays
- Computation is fast even for large programs (thousands of students)
- Database save operation is slower due to creating many
StudentRegistrationobjects - Use
stats_display=Falsefor production runs to reduce logging overhead
See Also
- Autoscheduler Controller - For automatic room/time assignment
- Student registration models in
esp/esp/program/models - Registration types and relationships
- Program module system