Pyomo目标定义错误:“ SyntaxError:生成器表达式必须加括号”

时间:2019-12-03 03:32:12

标签: pyomo

我是Pyomo的新手,尝试声明目标时遇到错误。如果可能的话,我宁愿使用def而不是 expr =

代码在下面。

# Import pyomo
from pyomo.environ import *

N = ['Harlingen', 'Memphis', 'Ashland']
M = ['NYC', 'LA', 'Chicago', 'Houston']

d = {('Harlingen', 'NYC'): 1956, \
     ('Harlingen', 'LA'): 1606, \
     ('Harlingen', 'Chicago'): 1410, \
     ('Harlingen', 'Houston'): 330, \
     ('Memphis', 'NYC'): 1096, \
     ('Memphis', 'LA'): 1792, \
     ('Memphis', 'Chicago'): 531, \
     ('Memphis', 'Houston'): 567, \
     ('Ashland', 'NYC'): 485, \
     ('Ashland', 'LA'): 2322, \
     ('Ashland', 'Chicago'): 324, \
     ('Ashland', 'Houston'): 1236 }

P = 2

model = ConcreteModel("warehouse location problem")

model.N = Set(dimen=1, initialize=N)
model.M = Set(dimen=1, initialize=M)
model.d = Param(model.N, model.M, within=PositiveIntegers, initialize=d)
model.P = Param(initialize=P)
model.y = Var(model.N, within=PositiveIntegers)
model.x = Var(model.N, model.M, bounds=(0,1))

def obj_rule(model):
    return sum(model.d[n,m] * model.x[n,m] for n in model.N, m in model.M)
model.obj = Objective(rule=obj_rule)

我收到的错误是

  File "warehouseLocation.py", line 35
    return sum(model.d[n,m] * model.x[n,m] for n in model.N, m in model.M)
              ^
SyntaxError: Generator expression must be parenthesized

感谢所有帮助

1 个答案:

答案 0 :(得分:2)

以这种方式编写目标函数

def obj_rule(model):
    return sum(model.d[n,m]* model.x[n,m] for n in model.N for m in model.M)
model.obj = Objective(rule=obj_rule)

要检查

model.obj.pprint()