繁体   English   中英

有没有更简单的方法来避免pyomo的这种索引键错误?

[英]Is there an easier way to avoid this kind of index key error of pyomo?

我正在使用pyomo处理LP模型,但是当我创建约束时,它显示“无法找到某个组合”的关键错误。 我知道列表所有组合都可以解决这个问题。 但真实数据有很多种组合。 有没有简单的方法来处理这个问题? 谢谢!这是一个简单的例子:

from pyomo.environ import *
import pandas as pd 
data = [['tom','A', 10], ['nick','A', 15], ['juli','B',14]]
df = pd.DataFrame(data, columns = ['Name','Type', 'Age'])  
#set
A = set(df['Name'])
B = set(df['Type'])
model = ConcreteModel()
#parameter
C= df.set_index(['Name','Type'])['Age'].to_dict()
#varibale
model.AB = Var(A,B,domain = NonNegativeReals)
#constraint1
def cons1(model,a,b):
    return(model.AB[a,b]<=C[a,b])
model.Cons1 = Constraint(A,B,rule = cons1)

使用C字典中的键来定义索引集:

from pyomo.environ import *
import pandas as pd 
data = [['tom','A', 10], ['nick','A', 15], ['juli','B',14]]
df = pd.DataFrame(data, columns = ['Name','Type', 'Age'])  

model = ConcreteModel()
#parameter
C= df.set_index(['Name','Type'])['Age'].to_dict()
#varibale
model.IJ = Set(initialize=C.keys())
model.AB = Var(model.IJ,domain = NonNegativeReals)
#constraint1
def cons1(model,a,b):
    return(model.AB[a,b]<=C[a,b])
model.Cons1 = Constraint(model.IJ,rule = cons1)

暂无
暂无

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

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