I'm wondering how I can translate this math constraint to gurobi python.

$$\forall a \in A, b \in B, x_{ab} \in \{0, 1\}$$

So far I have written:

xab = m.addVar(lb=0, ub=1, vtype=GRB.BINARY, name="xab")

But I'm not sure what to add for the constraints section...

m.addConstr(?? for a in A for b in B, "c0")

Is it really as simple as replacing ?? with xab? Any help would be appreciated! Thanks

from gurobipy import *
A = []; B = [] # You need to enter the data in these lists 

m = Model()
x = {} # Dictionary of variables
for a in A:
    for b in B:
        x[a, b] = m.addVar(lb=0, ub=1, vtype=GRB.BINARY, name="x_" +str(a) + str(b))

Note: Adding binary variables would constrain them to take values either 0 or 1. To add constraints involving these variables, you can use the following example syntax:

m.addConstr(x[a1, b1] + x[a2, b2] <= 10, name = 'c0')
  • $\begingroup$ This is a good starting point but it seems that the OP question was mainly about how to add constraints to a Gurobi model. $\endgroup$ Mar 20 '21 at 17:55
  • $\begingroup$ I'm confused. Does this edit address the issue? $\endgroup$ Mar 20 '21 at 20:24
  • $\begingroup$ Thank you very much for improving your answer. I think it is more informative now. Even better would be to show how to set a constraint with the number of operands depending on the problem's input data. $\endgroup$ Mar 22 '21 at 10:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.