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
525 stars 92 forks source link

Adding a constraint #122

Closed htheghost closed 2 years ago

htheghost commented 4 years ago

Hi all, I have constraints in an MILP where n successive variables have to take the same value. The basic idea would be:

m=Model()
[a = m.add_var(var_type=BINARY) for l in range(n_max)]
n = 3 # minimum number of successive variables which have to take the same value
for i in range(total):
    if a[i] ==1:
        m += xsum(a[l]==a[l-1] for l in range(i-n+1,i+n))>=n
        m += xsum(a[l] for l in range(i-n+1,i+n))>=n

The combination of these two lines would enforce that if a[i] takes the value 1 it is not isolated but within a group of at least m a's that are all 1.

This is not the only mathematical description that I tried in order to solve the problem, however the constrains were not added in the way I expected. I tried to define a separate variable a[i,1] which is defined as m+= a[i,1] ==bool(a[i-1]-a[i]) which would be False only if a[i] and a[i-1] are identical, however it didnt behave like that but was constant True.

I would be happy for any suggestion you have on how to solve this. Cheers, Henry

sebheger commented 2 years ago

Sorry, incomplete example.