排除反平行弧的 Pyomo 约束

  • 本文关键字:Pyomo 约束 排除 pyomo
  • 更新时间 :
  • 英文 :


我试图使用额外的约束来建模赋值问题,即解决方案不得包含反平行弧对,即如果在解决方案中 x[i,j]+x[j,i]<=1 必须对所有二进制变量成立;我已经复制了一个现有的分配解决方案,并尝试添加约束:

"""
Toy example for testing assignment without anti-parallel arcs
"""
from pyomo.environ import *
from pyomo.opt import *
opt = solvers.SolverFactory("glpk") 
# Change to "ipopt" for interior point solver
""" a larger instance that could be activated:
M = ['0', '1', '2','3','4','5','6']
W = ['0', '1', '2','3','4','5','6']
c = {('0','0'):0, ('0','1'):1, ('0','2'):0, ('0','3'):0, ('0','4'):0, ('0','5'):0, ('0','6'):0,
('1','0'):1, ('1','1'):0, ('1','2'):0, ('1','3'):0, ('1','4'):0, ('1','5'):0, ('1','6'):0,
('2','0'):0, ('2','1'):0, ('2','2'):0, ('2','3'):0, ('2','4'):0, ('2','5'):0, ('2','6'):0,
('3','0'):0, ('3','1'):0, ('3','2'):0, ('3','3'):0, ('3','4'):0, ('3','5'):0, ('3','6'):0,
('4','0'):0, ('4','1'):0, ('4','2'):0, ('4','3'):0, ('4','4'):0, ('4','5'):0, ('4','6'):0,
('5','0'):0, ('5','1'):0, ('5','2'):0, ('5','3'):0, ('5','4'):0, ('5','5'):0, ('5','6'):0,
('6','0'):0, ('6','1'):0, ('6','2'):0, ('6','3'):0, ('6','4'):0, ('6','5'):0, ('6','6'):0}    
"""
M = ['A', 'B', 'C']
W = ['D', 'E', 'F']
c = {('A','D'):1, ('A','E'):3, ('A','F'):3,
('B','D'):4, ('B','E'):3, ('B','F'):2,
('C','D'):5, ('C','E'):4, ('C','F'):2}

model = ConcreteModel()
model.x = Var(M, W, within=Binary)
model.z = Objective(expr = sum(c[i,j]*model.x[i,j]
for i in M for j in W), 
sense=maximize)
def all_m_assigned_rule (model, i):
return sum(model.x[i,j] for j in W) == 1
model.m = Constraint(M, rule=all_m_assigned_rule)
def all_w_assigned_rule (model, j):
return sum(model.x[i,j] for i in M) == 1
model.w = Constraint(W, rule=all_w_assigned_rule)

# additional model constraints that fail:
model.constraints = ConstraintList()
for i in I:
for j in range(i):
model.constraints.add((model.x[i,j]+model.x[j,i]) <= 1)

报告的基本错误是

KeyError                                  Traceback (most recent call last)
Input In [12], in <cell line: 48>()
48 for i in I:
49     for j in range(i):
---> 50         model.constraints.add((model.x[i,j]+model.x[j,i]) <= 1)
54 results = opt.solve(model)
56 model.x.get_values()

任何人都可以提供失败的解释吗? 解决问题的建议会很棒!

在您的示例中,model.xWM而不是按I(未定义)或整数(for j in range(i))进行索引。model.x[i,j]model.x[j,i]model.x的索引方式没有意义,因为WM具有不同的值。

最新更新