campioni
campioni

Reputation: 157

Add constraint for binary variable in CPLEX with Python

I am using docplex in Python to solve a ILP.

I would like to translate the following constraint in docplex.

[Constraint][1]

https://i.sstatic.net/OPhwe.png

I tried the following code:

#decision variables 

X_var = {(p, w, c, j): opt_model.binary_var(name="X_{0}_{1}_{2}_{3}".format(p, w, c, j))
          for p in set_OP for w in set_W for c in set_C for j in set_J}

T_var = {(w, w1, j-1, j): opt_model.binary_var(name="T_{0}_{1}_{2}_{3}".format(w, w1, j-1, j))
         for w in set_W for w1 in set_W for j in set_J}

#constraint
 cnrt_10 = {(p, w, w1, j-1, j): opt_model.add_constraint(ct=opt_model.sum(X_var[p-1, w, c, j-1] for c in set_C) + opt_model.sum(X_var[p, w1, c, j] for c in set_C) <= 1 + T_var[w, w1, j-1, j], 
                                                                ctname="cnrt10_{0}_{1}_{2}_{3}_{4}".format(p, w, w1, j-1, j)) for p in set_OP for w in set_W for w1 in set_W for j in set_J}

But it is giving the following error:

KeyError: (0, 1, 1, 0)

I've searched about, and it seems that this is an error related to an empty dictionary. I've tried many different ways to solve it, bus I was not able. Since I am new in Python and CPLEX, I think it is not really complicated. If someone could help me, I will be really grateful.

Thanks in advance,

Upvotes: 0

Views: 906

Answers (1)

Daniel Junglas
Daniel Junglas

Reputation: 5930

The problem is this: You are trying to access a variable with index (0, 1, 1, 0) but such a variable does not exist.

First of all, check whether the variable you reference is an X_var or a T_var. Remove one of the two from the constraint definition and see which one causes the error.

Then look hard at the indices with which you reference variables in the constraint and which variables you actually define.

From staring at your code, I guess the problem is this term in your constraint: X_var[p-1, w, c, j-1] p is taken from set_OP and j is taken from set_J. But variable X_var is defined with p from set_OP and j from set_J. So if you take the first element p0 from set_P then you have a variable X_var[p0, ., ., .] but you don't have a variable X_var[p0-1, ., ., .]. The latter is referenced by your constraint, though. Hence you will get a key error.

Upvotes: 1

Related Questions