排课问题的本质是将课程、教师和学生在合适的时间段内分配到合适的教室中,涉及到的因素较多,是一个多目标的调度问题,在运筹学中被称为时间表问题(Timetable Problem,TTP)。设一个星期有n个时段可排课,有m位教师需要参与排课,平均每位教师一个星期上k节课,在不考虑其他限制的情况下,能够推出的可能组合就有种,如此高的复杂度是目前计算机所无法承受的。因此众多研究者提出了多种其他排课算法,如模拟退火,列表寻优搜索和约束满意等。
Github:https://github.com/xiaochus/GeneticClassSchedule
环境
- Python 3.6
- prettytable
遗传算法原理
遗传算法(Genetic Algorithm)是模拟达尔文生物进化论的自然选择和遗传学机理的生物进化过程的计算模型,是一种通过模拟自然进化过程搜索最优解的方法。遗传算法的流程如下所示:
遗传算法首先针对待解决问题随机生成一组解,我们称之为种群(Population)。种群中的每个个体都是问题的解,在优化的过程中,算法会计算整个种群的成本函数,从而得到一个与种群相关的适应度的序列。如下图所示:
为了得到新的下一代种群,首先根据适应度对种群进行排序,从中挑选出最优的几个个体加入下一代种群,这一个过程也被称为精英选拔。新种群余下的部分通过对选拔出来的精英个体进行修改得到。
对种群进行修改的方法参考了生物DAN进化的方法,一般使用两种方法:变异
和交叉
。变异
的做法是对种群做一个微小的、随机的改变。如果解的编码方式是二进制,那么就随机选取一个位置进行0和1的互相突变;如果解的编码方式是十进制,那么就随机选取一个位置进行随机加减。交叉
的做法是随机从最优种群中选取两个个体,以某个位置为交叉点合成一个新的个体。
经过突变和交叉后我们得到新的种群(大小与上一代种群一致),对新种群重复重复上述过程,直到达到迭代次数(失败)或者解的适应性达到我们的要求(成功),GA算法就结束了。
基于遗传算法的排课优化
算法实现
首先定义一个课程类,这个类包含了课程、班级、教师、教室、星期、时间几个属性,其中前三个是我们自定义的,后面三个是需要算法来优化的。
class Schedule:
"""Class Schedule.
"""
def __init__(self, courseId, classId, teacherId):
"""Init
Arguments:
courseId: int, unique course id.
classId: int, unique class id.
teacherId: int, unique teacher id.
"""
self.courseId = courseId
self.classId = classId
self.teacherId = teacherId
self.roomId = 0
self.weekDay = 0
self.slot = 0
def random_init(self, roomRange):
"""random init.
Arguments:
roomSize: int, number of classrooms.
"""
self.roomId = np.random.randint(1, roomRange + 1, 1)[0]
self.weekDay = np.random.randint(1, 6, 1)[0]
self.slot = np.random.randint(1, 6, 1)[0]
接下来定义cost函数,这个函数用来计算课表种群的冲突。当被测试课表冲突为0的时候,这个课表就是个符合规定的课表。冲突检测遵循下面几条规则:
- 同一个教室在同一个时间只能有一门课。
- 同一个班级在同一个时间只能有一门课 。
- 同一个教师在同一个时间只能有一门课。
- 同一个班级在同一天不能有相同的课。
def schedule_cost(population, elite):
"""calculate conflict of class schedules.
Arguments:
population: List, population of class schedules.
elite: int, number of best result.
Returns:
index of best result.
best conflict score.
"""
conflicts = []
n = len(population[0])
for p in population:
conflict = 0
for i in range(0, n - 1):
for j in range(i + 1, n):
# check course in same time and same room
if p[i].roomId == p[j].roomId and p[i].weekDay == p[j].weekDay and p[i].slot == p[j].slot:
conflict += 1
# check course for one class in same time
if p[i].classId == p[j].classId and p[i].weekDay == p[j].weekDay and p[i].slot == p[j].slot:
conflict += 1
# check course for one teacher in same time
if p[i].teacherId == p[j].teacherId and p[i].weekDay == p[j].weekDay and p[i].slot == p[j].slot:
conflict += 1
# check same course for one class in same day
if p[i].classId == p[j].classId and p[i].courseId == p[j].courseId and p[i].weekDay == p[j].weekDay:
conflict += 1
conflicts.append(conflict)
index = np.array(conflicts).argsort()
return index[: elite], conflicts[index[0]]
使用遗传算法进行优化的过程如下,与上一节的流程图过程相同。
init_population
:随机初始化不同的种群。
mutate
:变异操作,随机对Schedule
对象中的某个可改变属性在允许范围内进行随机加减。
crossover
:交叉操作,随机对两个对象交换不同位置的属性。
evolution
:启动GA算法进行优化。
import copy
import numpy as np
from schedule import schedule_cost
class GeneticOptimize:
"""Genetic Algorithm.
"""
def __init__(self, popsize=30, mutprob=0.3, elite=5, maxiter=100):
# size of population
self.popsize = popsize
# prob of mutation
self.mutprob = mutprob
# number of elite
self.elite = elite
# iter times
self.maxiter = maxiter
def init_population(self, schedules, roomRange):
"""Init population
Arguments:
schedules: List, population of class schedules.
roomRange: int, number of classrooms.
"""
self.population = []
for i in range(self.popsize):
entity = []
for s in schedules:
s.random_init(roomRange)
entity.append(copy.deepcopy(s))
self.population.append(entity)
def mutate(self, eiltePopulation, roomRange):
"""Mutation Operation
Arguments:
eiltePopulation: List, population of elite schedules.
roomRange: int, number of classrooms.
Returns:
ep: List, population after mutation.
"""
e = np.random.randint(0, self.elite, 1)[0]
pos = np.random.randint(0, 2, 1)[0]
ep = copy.deepcopy(eiltePopulation[e])
for p in ep:
pos = np.random.randint(0, 3, 1)[0]
operation = np.random.rand()
if pos == 0:
p.roomId = self.addSub(p.roomId, operation, roomRange)
if pos == 1:
p.weekDay = self.addSub(p.weekDay, operation, 5)
if pos == 2:
p.slot = self.addSub(p.slot, operation, 5)
return ep
def addSub(self, value, op, valueRange):
if op > 0.5:
if value < valueRange:
value += 1
else:
value -= 1
else:
if value - 1 > 0:
value -= 1
else:
value += 1
return value
def crossover(self, eiltePopulation):
"""Crossover Operation
Arguments:
eiltePopulation: List, population of elite schedules.
Returns:
ep: List, population after crossover.
"""
e1 = np.random.randint(0, self.elite, 1)[0]
e2 = np.random.randint(0, self.elite, 1)[0]
pos = np.random.randint(0, 2, 1)[0]
ep1 = copy.deepcopy(eiltePopulation[e1])
ep2 = eiltePopulation[e2]
for p1, p2 in zip(ep1, ep2):
if pos == 0:
p1.weekDay = p2.weekDay
p1.slot = p2.slot
if pos == 1:
p1.roomId = p2.roomId
return ep1
def evolution(self, schedules, roomRange):
"""evolution
Arguments:
schedules: class schedules for optimization.
elite: int, number of best result.
Returns:
index of best result.
best conflict score.
"""
# Main loop .
bestScore = 0
bestSchedule = None
self.init_population(schedules, roomRange)
for i in range(self.maxiter):
eliteIndex, bestScore = schedule_cost(self.population, self.elite)
print('Iter: {} | conflict: {}'.format(i + 1, bestScore))
if bestScore == 0:
bestSchedule = self.population[eliteIndex[0]]
break
# Start with the pure winners
newPopulation = [self.population[index] for index in eliteIndex]
# Add mutated and bred forms of the winners
while len(newPopulation) < self.popsize:
if np.random.rand() < self.mutprob:
# Mutation
newp = self.mutate(newPopulation, roomRange)
else:
# Crossover
newp = self.crossover(newPopulation)
newPopulation.append(newp)
self.population = newPopulation
return bestSchedule
实验结果
下面定义了3个班,6种课程、教师和3个教室来对排课效果进行测试。
import prettytable
from schedule import Schedule
from genetic import GeneticOptimize
def vis(schedule):
"""visualization Class Schedule.
Arguments:
schedule: List, Class Schedule
"""
col_labels = ['week/slot', '1', '2', '3', '4', '5']
table_vals = [[i + 1, '', '', '', '', ''] for i in range(5)]
table = prettytable.PrettyTable(col_labels, hrules=prettytable.ALL)
for s in schedule:
weekDay = s.weekDay
slot = s.slot
text = 'course: {} \n class: {} \n room: {} \n teacher: {}'.format(s.courseId, s.classId, s.roomId, s.teacherId)
table_vals[weekDay - 1][slot] = text
for row in table_vals:
table.add_row(row)
print(table)
if __name__ == '__main__':
schedules = []
# add schedule
schedules.append(Schedule(201, 1201, 11101))
schedules.append(Schedule(201, 1201, 11101))
schedules.append(Schedule(202, 1201, 11102))
schedules.append(Schedule(202, 1201, 11102))
schedules.append(Schedule(203, 1201, 11103))
schedules.append(Schedule(203, 1201, 11103))
schedules.append(Schedule(206, 1201, 11106))
schedules.append(Schedule(206, 1201, 11106))
schedules.append(Schedule(202, 1202, 11102))
schedules.append(Schedule(202, 1202, 11102))
schedules.append(Schedule(204, 1202, 11104))
schedules.append(Schedule(204, 1202, 11104))
schedules.append(Schedule(206, 1202, 11106))
schedules.append(Schedule(206, 1202, 11106))
schedules.append(Schedule(203, 1203, 11103))
schedules.append(Schedule(203, 1203, 11103))
schedules.append(Schedule(204, 1203, 11104))
schedules.append(Schedule(204, 1203, 11104))
schedules.append(Schedule(205, 1203, 11105))
schedules.append(Schedule(205, 1203, 11105))
schedules.append(Schedule(206, 1203, 11106))
schedules.append(Schedule(206, 1203, 11106))
# optimization
ga = GeneticOptimize(popsize=50, elite=10, maxiter=500)
res = ga.evolution(schedules, 3)
# visualization
vis_res = []
for r in res:
if r.classId == 1203:
vis_res.append(r)
vis(vis_res)
优化结果如下,迭代到第68次时,课程安排不存在任何冲突。
...
Iter: 57 | conflict: 1
Iter: 58 | conflict: 1
Iter: 59 | conflict: 1
Iter: 60 | conflict: 1
Iter: 61 | conflict: 1
Iter: 62 | conflict: 1
Iter: 63 | conflict: 1
Iter: 64 | conflict: 1
Iter: 65 | conflict: 1
Iter: 66 | conflict: 1
Iter: 67 | conflict: 1
Iter: 68 | conflict: 0
选择1203班的课表进行可视化,如下所示,算法合理的安排了对应的课程。
+-----------+-----------------+-----------------+-----------------+-----------------+-----------------+
| week/slot | 1 | 2 | 3 | 4 | 5 |
+-----------+-----------------+-----------------+-----------------+-----------------+-----------------+
| 1 | | | course: 204 | | |
| | | | class: 1203 | | |
| | | | room: 3 | | |
| | | | teacher: 11104 | | |
+-----------+-----------------+-----------------+-----------------+-----------------+-----------------+
| 2 | | course: 204 | | course: 206 | |
| | | class: 1203 | | class: 1203 | |
| | | room: 3 | | room: 3 | |
| | | teacher: 11104 | | teacher: 11106 | |
+-----------+-----------------+-----------------+-----------------+-----------------+-----------------+
| 3 | | course: 203 | | | |
| | | class: 1203 | | | |
| | | room: 3 | | | |
| | | teacher: 11103 | | | |
+-----------+-----------------+-----------------+-----------------+-----------------+-----------------+
| 4 | course: 205 | | | | |
| | class: 1203 | | | | |
| | room: 1 | | | | |
| | teacher: 11105 | | | | |
+-----------+-----------------+-----------------+-----------------+-----------------+-----------------+
| 5 | course: 206 | | | course: 205 | course: 203 |
| | class: 1203 | | | class: 1203 | class: 1203 |
| | room: 2 | | | room: 3 | room: 1 |
| | teacher: 11106 | | | teacher: 11105 | teacher: 11103 |
+-----------+-----------------+-----------------+-----------------+-----------------+-----------------+