繁体   English   中英

在Pyomo或Gurobi中具有不同索引长度的多维变量

[英]Multidimensional Variable with Different index length in Pyomo or Gurobi

我想解决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循环来构造变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM