高级硬件设计中的研究课题需要通过一系列约束(唯一起始时间约束、依赖约束和资源约束)来优化一个调度过程。所以就开始学习pulp。
pulp官方网站,pulp是python的一个库,可以用来解决线性规划问题。
首先复习一下优化模型的三要素:
- 决策变量
- 目标函数
- 约束条件
A Set Partitioning Problem这个问题主要去解决这样一类问题——有时候需要将一个大集合(set)划分为小集合(subset),使每一个item只属于一个subset,但同时还需要满足一些其他的约束。
约束条件
- subset的个数最多是5
- subset的容量是4
- item属于且仅属于一个subset
目标函数
每个subset中item的最大ASCII与最小ASCII的差值最小(对应的happy越大)
"""
A set partitioning model of a wedding seating problem
Authors: lympassion
"""
from pulp import *
max_tables = 5
max_table_size = 4
guests = 'A B C D E F G H I J K L M N O P Q R'.split()
def happiness(table):
return abs(ord(table[0]) - ord(table[-1]))
possible_tables = [tuple(i) for i in allcombinations(guests, max_table_size)]
x = LpVariable.dicts('table', possible_tables, lowBound=0, upBound=1, cat=LpInteger) #
seat_model = LpProblem("seat model", LpMinimize)
# object function
seat_model += lpSum([happiness(i)*x[i] for i in possible_tables])
# constraint
seat_model += lpSum(x[i] for i in possible_tables) <= max_tables
for guest in guests:
seat_model += lpSum(x[i] for i in possible_tables if guest in i) == 1
seat_model.solve()
# print(seat_model.status)
print("The choosen tables are out of a total of %s:"%len(possible_tables))
for table in possible_tables:
if x[table].value() == 1:
print(table)
出错记录:
seat_model += lpSum([happiness(i)*x(i) for i in possible_tables])
TypeError: ‘dict’ object is not callablex = LpVariable.dict('table', possible_tables, lowBound=0, upBound=1, cat=LpInteger)
这里由于调用LpVariable.dict()
方法而出现了
dict->TypeError: not all arguments converted during string formatting错误