我无法为 RangeSet 的最后一个值提供 i+1 值,因此我想在约束中忽略它。但是,我无法这样做,因为 i 值始终作为默认值。所以,它不会进入if语句。我该如何解决这个问题?
import pyomo.environ as pyo
from pyomo.opt import SolverFactory
model = pyo.AbstractModel()
number_of_lane=2
number_of_vehicle=2
model.i = pyo.Param(within=pyo.NonNegativeIntegers, default=number_of_lane)
model.j = pyo.Param(within=pyo.NonNegativeIntegers, default=number_of_vehicle)
model.I = pyo.RangeSet(1, model.i)
model.J = pyo.RangeSet(1, model.j)
model.R = pyo.Param(default=0.5) #CAV's reaction (s)
model.D = pyo.Param(default=1.5) #Safety Distance (m)
model.lv = pyo.Param(default=4) #Length of vehicle (m)
model.xr = pyo.Param(model.I, model.J, within=pyo.NonNegativeIntegers, initialize=xr_cons)
model.x = pyo.Var(model.I, model.J, domain=pyo.NonNegativeReals, initialize=(0))
def lane_crossing_constraint_rule(m, i, j): #lane should be 2, vehicles will be the first one which is close to the intersection
m.i.pprint() #There is a problem about taking i and j value
if(m.i.value<number_of_vehicle): #Always comes equal!!!!
return (m.x[i,j]-m.xr[i,j])**2+(m.x[i+1,j]-m.xr[i+1,j])**2>=(m.lv+m.D)
else:
return pyo.Constraint.Skip
# the next line creates one constraint for each member of the set model.I
model.l1Constraint = pyo.Constraint(model.I, model.J, rule=lane_crossing_constraint_rule)
目前还不清楚您要尝试使用您选择的模型设置做什么。为什么选择
AbstractModel()
?您的示例不可重现,因为它缺少数据并且您没有构建模型实例。此外,我不确定您想通过从参数值初始化范围集大小来实现什么目的?
我认为你应该从
ConcreteModel()
开始,让一些东西发挥作用,并在需要时从那里开始构建。一次构建一点点,打印模型并验证它,然后添加到其中。
这是一个小例子,我认为它展示了您正在尝试做的一些事情。它是一个
ConcreteModel
,用于构建范围集、变量,并展示如何创建依赖于集合中索引值的约束 Lanes
import pyomo.environ as pyo
from pyomo.opt import SolverFactory
model = pyo.ConcreteModel()
number_of_lanes = 5
model.Lanes = pyo.RangeSet(1, number_of_lanes)
model.car_speed = pyo.Var(model.Lanes, domain=pyo.NonNegativeReals)
def lane_speed(model, lane):
if lane < 4:
return model.car_speed[lane] <= 60
return pyo.Constraint.Skip
model.lane_speed = pyo.Constraint(model.Lanes, rule=lane_speed)
model.pprint()
1 RangeSet Declarations
Lanes : Dimen=1, Size=5, Bounds=(1, 5)
Key : Finite : Members
None : True : [1:5]
1 Var Declarations
car_speed : Size=5, Index=Lanes
Key : Lower : Value : Upper : Fixed : Stale : Domain
1 : 0 : None : None : False : True : NonNegativeReals
2 : 0 : None : None : False : True : NonNegativeReals
3 : 0 : None : None : False : True : NonNegativeReals
4 : 0 : None : None : False : True : NonNegativeReals
5 : 0 : None : None : False : True : NonNegativeReals
1 Constraint Declarations
lane_speed : Size=3, Index=Lanes, Active=True
Key : Lower : Body : Upper : Active
1 : -Inf : car_speed[1] : 60.0 : True
2 : -Inf : car_speed[2] : 60.0 : True
3 : -Inf : car_speed[3] : 60.0 : True
3 Declarations: Lanes car_speed lane_speed