处理pyomo中这种关键错误的最佳方法是什么? [英] What is the best way to deal with this kind of key error in pyomo?

查看:55
本文介绍了处理pyomo中这种关键错误的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 problem. But the real data has many combinations. Is there any easy way to deal with this knid of problem? thanks!Here is a simple example:

这是一个类似的问题供参考:有没有更简单的方法可以避免pyomo的这种索引键错误?

This is a similar question for reference: 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)

推荐答案

您之前的问题 并修复我认为您的第二个约束中的错字,技巧是在总和中迭代 B 时检查 (a,b) 对是否在集合 IJ 中:

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)

这篇关于处理pyomo中这种关键错误的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆