Skip to content Skip to sidebar Skip to footer

What Is The Best Way To Deal With This Kind Of Key Error In Pyomo?

I am working on a LP model with pyomo,but when I create constraint, it shows a key error of 'can not find a certain combination'. I know list all the combinations can solve this pr

Solution 1:

Starting with the solution given in your previous question and fixing what I think is a typo in your second constraint, the trick is to check if the (a,b) pair is in the set IJ when iterating over B in the sum:

from pyomo.environ import *
import pandas as pd 
data = [['tom','A', 10], ['nick','A', 15], ['juli','B',14], ['juli','A',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.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)

def cons2(model,a):
    return(sum(model.AB[a,b] for b in B if (a,b) in model.IJ)<=1)
model.Cons2 = Constraint(A,rule = cons2)

Post a Comment for "What Is The Best Way To Deal With This Kind Of Key Error In Pyomo?"