IBMDecisionOptimization / docplex-examples

These samples demonstrate how to use the DOcplex library to model and solve optimization problems.
https://ibmdecisionoptimization.github.io/
Apache License 2.0
396 stars 228 forks source link

docplex: Error while placing 'if' condition inside the constraint #39

Closed Brad73 closed 3 years ago

Brad73 commented 3 years ago

Hi,

I require a help. I am getting an error when trying to place an if condition inside this constraint:

mdl.add_constraints(mdl.sum(x[i,j] for i in m if i,j in A)>=1 for j in n)

Error:

 File "<ipython-input-53-94c3e0ea9065>", line 5
    mdl.add_constraints(mdl.sum(x[i,j] for i in m if i,j in A)>=1 for j in n )
                               ^
SyntaxError: Generator expression must be parenthesized

Tried several times but couldn't resolve this.

For this model, the variables were defined as:

m=[i for i in range(1,8)]
n=[i for i in range(1,11)]
A=[(1, 1),(1, 3),(2, 1),(2, 6),(2, 8),(3, 2),(3, 5),(3, 7),(4, 1),(4, 8),
   (4, 9),(5, 2),(5, 4),(5, 7),(6, 1),(6, 3),(6, 5),(6, 10),(7, 4),(7, 5),(7, 6),(7, 9)]

and the decision variables are:

x=mdl.binary_var_dict(A,name='x')

It would be of great help if you could provide a solution to appropriately construct this constraint. Many THANKS.

vlkong commented 3 years ago

This is a pure python issue. In your generator expression, if i,j in A is malformed. A is a list of tuples, so you want i,j to be a tuple. The right expression is: if (i,j) in A

Note: if all you do on 'm' and 'n' is iterating over the list, your code will be more efficient if you just write:

m = range(1,8)
n = range(1,11)

Likewise, unless you need A as a list, if all you do is check that tuples are in A, use a set.

Brad73 commented 3 years ago

Thanks for the help.