有没有更简单的方法来避免这种pyomo的索引键错误? [英] Is there an easier way to avoid this kind of index key error of pyomo?

查看:162
本文介绍了有没有更简单的方法来避免这种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:

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词典中的键定义索引集:

Use the keys from the C dictionary to define your indexing set:

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)

这篇关于有没有更简单的方法来避免这种pyomo的索引键错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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