我正在使用Python解决一个优化问题,我必须优化一个理论医院的时间表.本时间表有3栏代表不同的剧院,每行9个时段代表每天的时段数.
每个时间段都被一个手术占用,描述每个手术的一个值是它是否需要麻醉师,而这个问题的一个限制是,在所有手术室的任何给定时间段内,你不能有超过两个的需要.
因为我的时间表是这样表示的:
Theatre 1 | Theatre 2 | Theatre 2 |
---|---|---|
Slot 1 | Slot 1 | Slot 1 |
Slot 2 | Slot 2 | Slot 2 |
Slot 3 | Slot 3 | Slot 3 |
Slot 4 | Slot 4 | Slot 4 |
Slot 5 | Slot 5 | Slot 5 |
Slot 6 | Slot 6 | Slot 6 |
Slot 7 | Slot 7 | Slot 7 |
Slot 8 | Slot 8 | Slot 8 |
Slot 9 | Slot 9 | Slot 9 |
我创建了这个函数来判断3个手术室中的一个插槽中的手术,如果所需的数量超过2的限制,则返回false,如果所需的数量在限制之内则返回true.
def AnaesthetistsWithinLimit(timetable, anaesthetistLimit):
# Index of column, theatre, max 3
for i in range(len(timetable)):
# Index of row, slot, max 9
for j in range(len(timetable[0])):
comparisonArray = [timetable[0][j], timetable[1][j], timetable[2][j]]
anaesthetistCount = 0
for y in comparisonArray:
if y["requires_anaesthetist"] == "Yes":
anaesthetistCount += 1
if anaesthetistCount > anaesthetistLimit:
print("Constraint breached:")
print(" " + str(anaesthetistCount) + " anaesthetists were required")
print(" limit is " + str(anaesthetistLimit) + " anaesthetists.")
return False
return True
为了生成一个解决方案,我使用一种方法来创建一个随机的插槽,从一个包含所有可能的手术及其细节的csv文件中提取,该文件包含在surgeryData中.
def RandomiseTimetable(timetable, surgeryData):
for x in range(3):
column = []
for y in range(9):
randomIndex = random.randint(0, len(surgeryData) - 1)
randomRow = surgeryData.iloc[randomIndex]
column.append({
"surgery": randomRow["surgery"],
"name": randomRow["name"],
"requires_anaesthetist": randomRow["requires_anaesthetist"],
})
timetable.append(column)
return timetable
随机化时间表是可行的,因为我可以在编辑器中看到,表会随着每次运行而改变,但是当我试图测试这个约束,并生成一个新的解决方案直到满足时,它要么根本不生成新的解决方案,要么继续生成,迫使我手动停止它.
这里我想判断当前所需金额是否在限额内,如果不为真,则生成一个新的解决方案.然后,一旦为真,它就应该跳出while循环,并通过执行适应度函数来继续.
while AnaesthetistsWithinLimit(timetable, 2) != True:
timetable = RandomiseTimetable(timetable, surgeryData)
FitnessFunction(timetable, True)
然而,正如这里所看到的,它只是继续运行限制判断器,而从未实际生成新的解决方案.
Constraint breached:
3 anaesthetists were required
limit is 2 anaesthetists.
Constraint breached:
3 anaesthetists were required
limit is 2 anaesthetists.
Constraint breached:
3 anaesthetists were required
limit is 2 anaesthetists.
Constraint breached:
3 anaesthetists were required
limit is 2 anaesthetists.
Constraint breached:
3 anaesthetists were required
limit is 2 anaesthetists.
Constraint breached:
3 anaesthetists were required
limit is 2 anaesthetists.
...
我不知道我错过了什么.如果检测到漏洞,麻醉师判断器返回false,如果没有,则返回true.因此,当这个测试返回false时,生成一个新的解决方案.据我所知,Python通过引用传递列表,所以函数应该使用它下面一行生成的时间表.
我可能误解了什么?