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 文档中引用的一些示例模型:https://pyomo.readthedocs.io/en/latest/tutorial_examples.html。
您不需要使用 for
循环来构造变量。
诀窍在于定义用于索引变量的索引集。 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])
我想解决 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 文档中引用的一些示例模型:https://pyomo.readthedocs.io/en/latest/tutorial_examples.html。
您不需要使用 for
循环来构造变量。
诀窍在于定义用于索引变量的索引集。 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])