我想用Python解决一个优化问题。我试图定义一个变量 x_{g,h} ,其中索引 g 属于集合 G ,索引 h 属于集合 H(g) ,即索引 h 的集合对于不同的索引 g 是不同的。有没有办法在 Pyomo 或 Gurobi-Python 中使用这些索引定义变量 x ?
在 Pyomo 中,我尝试在循环中定义它,例如
for g in p.keys():
for h in range(0,p.rop[g].npairs,1):
model.x_gen_h = Var(g,h,within=NonNegativeReals)
我收到此错误:
TypeError: 'int' object is not iterable.
我感谢任何帮助或评论!
技巧在于定义用于索引变量的索引集。 Pyomo 不支持循环单个索引并将它们一次添加到 Var 索引中。您应该使用一些巧妙的 Python 代码来构建整个索引集。例如,您可以使用类似的方法来过滤掉您想要的索引:
m = ConcreteModel()
m.g = Set(initialize=[1,2,3])
h = {1:['a','b'], 2:['b','c'], 3:['c','d']}
m.h_all = Set(initialize=set(sum(h.values(),[]))) # Extract unique h values
# Initialize set to be entire cross product of g and h and then filter desired values
m.hg = Set(initialize=m.g*m.h_all, filter=lambda m,g,hi:hi in h[g])
m.x = Var(m.hg, within=NonNegativeReals)
更好的选择是:
h = {1:['a','b'], 2:['b','c'], 3:['c','d']}
m.hg = Set(initialize=list((i,j) for i in h.keys() for j in h[i])
我会看一下 Pyomo 文档中引用的一些示例模型:https://pyomo.readthedocs.io/en/latest/tutorial_examples.html.
您不需要使用
for
循环来构造变量。
定义索引变量的自然方法是通过 pyomo
RangeSet
而不是 Set
。
每个 RangeSet
定义不同维度的索引值。
可以使用多个范围集作为参数来初始化变量,从而产生使用范围集的笛卡尔积中的元素进行索引的变量。
相同的范围集可能会在一组变量的声明中作为参数出现多次,这在here
有很好的解释