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

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

我正在使用 pyomo 处理 LP 模型,但是当我创建约束时,它显示 'can not find a certain combination' 的关键错误。我知道列出所有组合可以解决这个问题。但是真实的数据有很多组合。有什么简单的方法可以解决这个问题吗?谢谢!这是一个简单的例子:

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)