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

2024-10-01 11:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用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)

我有个错误:

^{pr2}$

我感谢任何帮助或评论!在


Tags: 方法informodel定义varrangekeys
2条回答

诀窍在于定义用于索引变量的索引集。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)

更好的选择是:

^{pr2}$

我想看看Pyomo文档中引用的一些示例模型:https://pyomo.readthedocs.io/en/latest/tutorial_examples.html。在

您不应该使用for循环来构造变量。在

相关问题 更多 >