我正在使用 PYOMO,我想在“P_constraint_rule”中实现逻辑或,但我做不到。
我的模型有一些部分:
model.s = Param(within=NonNegativeIntegers)
model.S = RangeSet(1, model.s)
model.f = Param(within=NonNegativeIntegers)
model.F = RangeSet(1, model.f)
model.p = Param(within=NonNegativeIntegers)
model.P = RangeSet(0, model.p)
model.m = Param(within=NonNegativeIntegers)
model.M = RangeSet(1, model.m)
model.g = Param(model.M, default=5.0)
model.b2 = Param(model.F,model.F, within=Binary, default=0)
model.xf1f2 = Var(model.F, model.F, within=Binary)
model.y = Var(model.M, within=Binary)
model.xf = Var(model.F, within=Binary)
model.aff = Param(model.F,model.F, within=NonNegativeIntegers, default=0)
...
model.x = Var(model.index_sfpm, within=Binary)
model.b1 = Param(model.index_sfpm, within=Binary, default=0)
def Obj_rule(model):
expr = 0.0
for (s,f,p,m) in model.index_sfpm:
expr += model.g[m] * model.xf[f] * model.b1[s,f,p,m] * model.x[s,f,p,m]
for m in model.M:
expr += model.g[m] * model.y[m]
return expr
model.OBJ = Objective(rule=Obj_rule, sense=maximize)
def P_constraint_rule (model, f1, f2):
expr = 0.0
for (s,m) in model.index_sm:
expr += model.b2[f1,f2] * model.xf[f1] * model.b1[s,f1,1,m] * model.x[s,f1,1,m]
expr += model.xf[f2] * model.b1[s,f2,1,m] * model.x[s,f2,1,m]
例如在我的 .dat 中:param aff:= 1 7 10
return expr == model.aff[f1,f2] | expr == 0
model.PConstraint = Constraint(model.index_f1f2, rule=P_constraint_rule)
当我使用“|”时,出现以下错误:
ERROR: Rule failed when generating expression for constraint PConstraint with index (7, 3):
TypeError: unsupported operand type(s) for |: 'int' and '_SumExpression' ERROR: Constructing component 'PConstraint' from data=None failed:
TypeError: unsupported operand type(s) for |: 'int' and '_SumExpression' [ 1.72] Pyomo Finished ERROR: Unexpected exception while running model:
unsupported operand type(s) for |: 'int' and '_SumExpression'
当我使用“||”
ERROR: Unexpected exception while loading model:
invalid syntax
当该约束被注释时,模型和 gurobi 运行良好。
有人可以帮助我解决这些错误吗?
还有另一种使用量词的可能性吗?不等式 P1.constraint 应该对 model.index_f1f2 有效 等式 P2Constraint 应该对 model.F 的 2 个元素或 model.index_f1f2 的 1 个元素有效,如下所示:
def P1_constraint_rule (model, f1, f2):
expr = 0.0
for (s,m) in model.index_sm:
expr += model.b2[f1,f2] * model.xf[f1] * model.b1[s,f1,1,m] * model.x[s,f1,1,m]
expr += model.xf[f2] * model.b1[s,f2,1,m] * model.x[s,f2,1,m]
return expr <= model.aff[f1,f2]
model.P1Constraint = Constraint(model.index_f1f2, rule=P1_constraint_rule)
def P2_constraint_rule (model, f1, f2):
expr = 0.0
for (s,m) in model.index_sm:
expr += model.b2[f1,f2] * model.xf[f1] * model.b1[s,f1,1,m] * model.x[s,f1,1,m]
expr += model.xf[f2] * model.b1[s,f2,1,m] * model.x[s,f2,1,m]
#this equation should be valid for 2 elements of model.F or 1 element of model.index_f1f2
return expr == model.aff[f1,f2]
model.P2Constraint = Constraint(model.index_f1f2, rule=P2_constraint_rule)
提前谢谢你,拉拉