coin-or / python-mip

Python-MIP: collection of Python tools for the modeling and solution of Mixed-Integer Linear programs
Eclipse Public License 2.0
530 stars 92 forks source link

Adding constraint with all variables' coefficients equal to zero #281

Closed IlyaShaternik closed 2 years ago

IlyaShaternik commented 2 years ago

Using mip.xsum you can add constraint to model, where all variables' coefficients are equal to zero. Consider the following code.

from mip import *

A = [[1.0, 2.0], [0.0, 0.0]]
B = [5.0, 6.0]

m = Model(solver_name='CBC')

x = [m.add_var('x', var_type=INTEGER) for i in range(2)]

m += xsum(x[i] * A[0][i] for i in range(2)) <= B[0]
m += xsum(x[i] * A[1][i] for i in range(2)) <= B[0]

If after that I run the following:

for c in m.constrs:
    print(c.name)

I get:

constr(0)
Invalid row index (1), valid range is [0,1). At C:/projects/Cbc/src/Cbc_C_Interface.cpp:1598

If you don't use mip.xsum or use regular sum instead:

m += x[0] * A[0][0] + x[1] * A[0][1] <= B[0]
m += x[0] * A[1][0] + x[1] * A[1][1] <= B[0]

Then you get noted by an exception:

Traceback (most recent call last):
  File "d:\work\testpy\test.py", line 14, in <module>
    m += x[0] * A[1][0] + x[1] * A[1][1] <= B[0]
  File "C:\ProgramData\Anaconda3\envs\ppp\lib\site-packages\mip\model.py", line 203, in __iadd__
    raise TypeError("type {} not supported".format(type(other)))
TypeError: type <class 'bool'> not supported

Also if you create Model object with solver_name='GRB', you still can add that kind of constraint to model, but you won't get an error, while iterating over constrs.

Operating System: Windows 10 Python version: 3.10.4 Python-MIP version: 1.13.0

sebheger commented 2 years ago

Thanks @IlyaShaternik for reporting the issue.

I can reproduce it with version 1.13.

I already fixed the arithmetic, so on master everything works fine for cbc. It will be available with the next release soon.