Pyomo对特定范围的约束

时间:2017-07-25 19:57:10

标签: python optimization constraints pyomo

以下是我尝试运行的优化代码的一部分。

from pyomo.environ import *
model = ConcreteModel()

## Define sets 
model.k = Set(initialize=['Diesel','Diesel_hybrid', 'Battery_electric'], doc='Vehicle Type')
model.i = Set(initialize=[0,1,2,3,4,5], doc='Age')
model.t = Set(initialize=[2018,2019,2020,2021,2022,2023], doc='Years')

## Define variables 
model.P = Var(model.k, model.t, bounds=(0,None), doc='number of k type vehicle purchased in year t')
model.A = Var(model.k, model.i, model.t, bounds=(0,None), doc='number of k type i year old bus in use at the end of year t')
model.R = Var(model.k, model.i, model.t, bounds=(0,20), doc='number of k type i year old bus salvaged at year t')

我试图写一个约束,说明,对于公共汽车的年龄i <= 4,救助的公交车数R [k,i,t] = 0 我尝试了以下内容。它似乎不起作用。

def constraint_5(model,k,t):
    if (i<=4):
        return model.R[k,i,t] == 0

我也尝试过定义一个子集。那也行不通。

model.sal = Set(initialize=[0,1,2,3,4], doc='Minimum age in usage')
def constraint_5(model,k,t):
    for i in model.w:
        return model.R[k,i,t] == 0

任何人都可以帮助我吗?感谢

1 个答案:

答案 0 :(得分:1)

您可以通过索引所有集合上的约束并使用Constraint.Skip跳过为不需要的索引添加约束来实现此目的

def constraint_5(model,k,i,t):
    if i<=4:
        return model.R[k,i,t] == 0
    return Constraint.Skip
model.con5 = Constraint(model.k,model.i,model.t,rule=constraint_5)

或者您可以在您创建的子集上索引约束

def constraint_5(model,k,i,t):
    return model.R[k,i,t] == 0
model.con5 = Constraint(model.k,model.sal,model.t,rule=constraint_5)