【问题标题】:What is the best way to deal with this kind of key error in pyomo?在pyomo中处理这种关键错误的最佳方法是什么?
【发布时间】:2019-05-07 09:13:43
【问题描述】:

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

这是一个类似的问题供参考: Is there an easier way to avoid this kind of index key error of pyomo?

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)
#constraint2
def cons2(model,a):
    return(sum(model.AB[a,b]<=C[a,b] for b in B)<=1)
model.Cons2 = Constraint(A,rule = cons2)

【问题讨论】:

  • 错误:使用索引 nick 为约束 Cons2 生成表达式时规则失败:KeyError:“索引'('nick','B')'对于索引组件'AB'无效”错误:构造来自 data=None 的组件 'Cons2' 失败:KeyError: "Index '('nick', 'B')' is not valid for indexed component 'AB'"

标签: python pyomo


【解决方案1】:

your previous question 中给出的解决方案开始并修复我认为您的第二个约束中的错字,诀窍是在迭代@987654323 时检查(a,b) 对是否在集合IJ 中@总和:

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)

【讨论】:

    猜你喜欢
    • 2021-03-01
    • 1970-01-01
    • 2021-09-10
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多