加载模型时出现意外异常:(0,0)



我刚开始使用pyomo框架和python。我正在努力解决简单的模型。当我制定目标函数时,我在运行代码之前收到以下错误

KeyError:(0,0(

以下是问题的表述:配方

代码:

from pyomo.environ import *  
N = 3
M = 4
P = 3
d = {(1, 1): 1.7, (1, 2): 7.2, (1, 3): 9.0, (1, 4): 8.3,
(2, 1): 2.9, (2, 2): 6.3, (2, 3): 9.8, (2, 4): 0.7,
(3, 1): 4.5, (3, 2): 4.8, (3, 3): 4.2, (3, 4): 9.3}
seq = ConcreteModel()
seq.Locations = range(N) #Set N
seq.Customers = range(M) #Set M
seq.x = Var(seq.Locations, seq.Customers, bounds=(0.0, 1.0)) #x[n,m]
seq.y = Var(seq.Locations, within=Binary)
seq.obj=Objective(expr = sum( d[n,m]*seq.x[n,m] for n in seq.Locations for m in seq.Customers))
seq.single_x = ConstraintList()
for m in seq.Customers:
seq.single_x.add(
sum(seq.x[n,m] for n in model.Locations ) == 1.0)

seq.bound_y = ConstraintList()
for n in seq.Locations:
for m in seq.Customers:
seq.bound_y.add( seq.x[n,m] <= seq.y[n] )
seq.num_facilities = Constraint(
expr=sum( seq.y[n] for n in seq.Locations) == P)

什么可能是问题?非常感谢。

您得到的关键错误是因为您的字典d没有[0,0]的条目。

我的建议是,你把所有的东西都纳入模型中(见下面我的编辑(。这样你就可以";漂亮的印刷品;该模型使在构建时进行故障排除变得非常容易。

祝你好运!

from pyomo.environ import *  
N = 3
M = 4
P = 3
d = {(1, 1): 1.7, (1, 2): 7.2, (1, 3): 9.0, (1, 4): 8.3,
(2, 1): 2.9, (2, 2): 6.3, (2, 3): 9.8, (2, 4): 0.7,
(3, 1): 4.5, (3, 2): 4.8, (3, 3): 4.2, (3, 4): 9.3}
seq = ConcreteModel()
###  SETS
seq.Locations = Set(initialize = list(range(1, N+1))) #Set N  # note the capitalization Set, the pyomo type
seq.Customers = Set(initialize = list(range(1, M+1))) #Set M
### PARAMS
seq.d = Param(seq.Locations, seq.Customers, initialize=d)
### VARS
seq.x = Var(seq.Locations, seq.Customers, bounds=(0.0, 1.0)) #x[n,m]
seq.y = Var(seq.Locations, within=Binary)
seq.obj=Objective(expr = sum( seq.d[n,m]*seq.x[n,m] for n in seq.Locations for m in seq.Customers))
seq.single_x = ConstraintList()
for m in seq.Customers:
seq.single_x.add(
sum(seq.x[n,m] for n in seq.Locations ) == 1.0)

seq.bound_y = ConstraintList()
for n in seq.Locations:
for m in seq.Customers:
seq.bound_y.add( seq.x[n,m] <= seq.y[n] )
seq.num_facilities = Constraint(
expr=sum( seq.y[n] for n in seq.Locations) == P)
seq.pprint()

最新更新