1
$\begingroup$

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?

$\endgroup$
1

2 Answers 2

3
$\begingroup$
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')
$\endgroup$
3
  • $\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, 2021 at 17:55
  • $\begingroup$ I'm confused. Does this edit address the issue? $\endgroup$ Mar 20, 2021 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, 2021 at 10:33
2
$\begingroup$
x = m.addVars(A, B, vtype=GRB.BINARY, name="x")

then x becomes a dict whose key is a tuple (a,b), and the value is a Var.

To add a set of constraints

m.addConstrs(x[a,b]+y[a,b]<=c[a,b] for a in A for b in B)
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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