I am trying to model assignment problems with the additional constraint that the solution must not contain pairs of anti-parallel arcs, i.e. if in the solution x[i,j]+x[j,i]<=1 must hold for all Binary variables; I have copied an existing solution for assignment and try to add the constraints:
"""
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)
The essential reported error is
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()
Can anyone provide an explanation of the failure? A suggestion that fixes the problem would be great!