forked from henrymwestfall/course-scheduler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solver.py
227 lines (187 loc) · 8.19 KB
/
solver.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
from pulp import LpProblem, LpAffineExpression, LpVariable, LpConstraint, LpStatus
from scipy.cluster.vq import vq, kmeans2, whiten
import numpy as np
from classes.student import Student
from classes.teacher import Teacher
from classes.course import *
from classes.schedule import *
from utils import summation
from problem_generator import ToyProblem
import matplotlib.pyplot as plt
def tag_generator():
tag = 0
while True:
yield tag
tag += 1
class Problem:
def __init__(self):
ret = self.load_toy_problem()#self.load_students_and_teachers_and_courses()
self.students, self.teachers, self.courses = ret
self.problem = LpProblem("Toy_Problem")
self.existing_sections = []
@property
def status(self):
return self.problem.status
def add_constraints(self):
self.add_constraints_from_individuals()
self.define_global_constraints()
def solve(self):
self.add_constraints()
self.problem.solve()
self.create_final_sections()
def display_result(self):
print(f"Solution is {LpStatus[self.status]}")
for section in self.existing_sections:
print(section)
print(self.students[0]._schedule)
def load_students_and_teachers_and_courses(self):
"""
Return a tuple containing a list of Teacher and Student objects.
This loads the courses and adds them to the objects request/qualification
lists.
"""
# load the raw data
# TODO: load from a file of some sort
num_courses = 5
student_requests = [
[0, 1, 3],
[0, 2, 3],
[0, 2, 4],
[1, 3, 4],
[0, 1, 2],
[1, 2, 3]
]
teacher_qualifs = [
[0, 1, 3],
[0, 2, 4],
[1, 2, 3]
]
rawCourses = [(str(i), CourseType.CORE) for i in range(num_courses)] # example course already in list
rawStudentRequests = {i: reqs for i, reqs in enumerate(student_requests)} # map student name to requests (strings)
rawStudentGrades = {i: 12 for i in range(len(student_requests))} # map student name to the grade they're in
rawTeacherQualifications = {i: qualifs for i, qualifs in enumerate(teacher_qualifs)} # map teacher name to qualifications (strings)
rawTeacherRequestedOpenPeriods = {i: 0 for i in range(len(teacher_qualifs))} # map teacher name to requested open periods
# create tag generator
tg = tag_generator()
# create Courses, Students, and Teachers
courses = {} # maps course name to object
for c in rawCourses:
courses[c[0]] = Course(*c)
allCourses = list(courses.values())
students = []
for index, requestList in rawStudentRequests.items():
student = Student(next(tg), allCourses)
# set student grade to rawStudentGrades[index]
students.append(student)
student.requestAll([courses[str(c)] for c in requestList])
teachers = []
for index, qualifications in rawTeacherQualifications.items():
qualifications_with_course_objects = [courses[str(q)] for q in qualifications]
teacher = Teacher(next(tg), allCourses)
teacher.addQualifications(qualifications_with_course_objects)
# TODO: add open period requests from rawTeacherRequestedOpenPeriods[index]
teachers.append(teacher)
return students, teachers, list(courses.values())
def load_toy_problem(self):
p = ToyProblem(num_teachers=24, num_students=200, num_courses=20, num_periods=8, num_pathways=2)
return p.students, p.teachers, p.all_courses
def add_constraints_from_individuals(self):
"""
Add constraints from constraining_students and constraining_teachers to problem.
"""
for student in self.students:
self.add_constraints_from_individual(student, "student")
for teacher in self.teachers:
self.add_constraints_from_individual(teacher, "teacher")
def add_constraints_from_individual(self, individual, individual_type_string):
for constraint in individual.getConstraints():
assertion_message = f"{individual_type_string} constraint was illegal"
assert isinstance(constraint, LpConstraint), assertion_message
self.problem += constraint
def get_sections_need_teachers_constraints(self):
"""
Define the LpConstraint ensuring that each section assigned to a student
has a qualified teacher assigned to it also.
"""
all_constraints = []
for student in self.students:
for period, lpVars in enumerate(student._schedule._lpVars):
for class_id, attending in enumerate(lpVars):
# get corresponding qualified teachers
teacher_assignment_variables = []
for teacher in self.teachers:
if teacher.getQualificationVector()[class_id] == 1:
teacher_assignment_variables.append(teacher._schedule._lpVars[period][class_id])
c = summation(teacher_assignment_variables) >= attending
all_constraints.append(c)
"""
Using getGlobalConstr:
allConstrs = []
for course in self.courses:
allConstrs.append(course.getGlobalConstr())
return allConstrs
"""
return all_constraints
def define_global_constraints(self):
"""
Add constraints that affect multiple individuals simultaneously to problem.
"""
# set is ideal, but LpConstraints are unhashable
all_constraints = []
all_constraints += self.get_sections_need_teachers_constraints()
for c in all_constraints:
assert isinstance(c, LpConstraint), "global constraint was illegal"
self.problem += c
def create_final_sections(self):
"""
Return a list of the final Section objects with Students and Teachers added.
"""
# build all sections
for individual in self.students + self.teachers:
new_sections = individual.createSections() # method not implemented yet
for section in new_sections:
for existing_section in self.existing_sections:
if section == existing_section:
break
else:
# the section doesn't exist yet, so add it to the existing sections
individual.addToSection(section)
self.existing_sections.append(section)
continue
# the section already exists, so add the student/teacher there
individual.addToSection(existing_section)
def sectionSizeHist(self):
"""
Returns data for creating a histogram for section size
Returns: Dictionary of class size to frequency.
"""
ret = {}
for sect in self.existing_sections:
if len(sect._students) in ret.keys():
ret[len(sect._students)] += 1
else:
ret[len(sect._students)] = 1
sectSizeFig, sectSizeAx = plt.subplots()
sectSizeAx.bar(ret.keys(), ret.values())
sectSizeAx.set_xlabel("Class size")
sectSizeAx.set_ylabel("Frequency")
sectSizeAx.set_title("Class Size Distribution")
plt.show()
def sectSizeDev(self):
"""
Returns equation for measuring
"""
ret = []
avClass = len(self.students) / len(self.teachers)
for sect in self.existing_sections:
sectStudVariables = []
for stud in sect._students:
sectStudVariables.append(stud._schedule._lpVars[sect._period][sect._courseCode])
ret.append(sectStudVariables)
return LpAffineExpression(32*len(self.existing_sections) - summation(ret))
if __name__ == "__main__":
#solve()
p = Problem()
p.solve()
p.display_result()
p.sectionSizeHist()