Can't get constraint, like 0 <= 1, by name
AnsweredI use
model.addConstr(x.sum(i, '*') <= 1, f"constr_{i}")
However, if x.select(i, '*') is empty, the constraint cannot be get by name.
m = Model()
c = m.addConstr(0 <= 1, "123")
m.update()
assert c is not None
cc = m.getConstrByName("123")
assert cc is None
How can I get this constraint? I want to keep the number of the constraints the same as my dict, so I can't just skip these trivial constraints.
PS: I found a workaround to this problem: just change the zero left hand side to LinExpr(0)
#c = m.addConstr(0 <= 1, "123")
c = m.addConstr(LinExpr(0) <= 1, "123")
0
-
You could also pass the constraint name to Model.addConstr() using the \(\texttt{name}\) keyword argument instead of as a positional argument:
c = m.addConstr(0 <= 1, name='c123')
m.update()
print(c.ConstrName) # c1230 -
I think your point is interesting, with name keyword, getConstrByName works ok, however, it doesn't work without the keyword.
m = Model()
c1 = m.addConstr(0 <= 1, "c1")
c2 = m.addConstr(0 <= 1, name="c2")
m.update()
assert c1 is not None and c2 is not None
cc1 = m.getConstrByName("c1") # cannot get c1
assert cc1 is None
cc2 = m.getConstrByName("c2") # can get c2. Why?
assert cc2 is not None0 -
Right, I was suggesting a different workaround. We have logged this as a bug; thanks for reporting it!
0 -
Thanks a lot!
0
Please sign in to leave a comment.
Comments
4 comments