1

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?

SecretAgentMan
  • 1,895
  • 2
  • 13
  • 39
a6623
  • 121
  • 4
  • Implementing a complete problem is elaborated here: https://or.stackexchange.com/questions/797/how-to-model-a-mixed-integer-linear-programming-formulation-in-python-using-guro – Mostafa Mar 19 '21 at 21:19

2 Answers2

3
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')
Pramesh Kumar
  • 411
  • 3
  • 9
  • This is a good starting point but it seems that the OP question was mainly about how to add constraints to a Gurobi model. – Hexaly Mar 20 '21 at 17:55
  • I'm confused. Does this edit address the issue? – Pramesh Kumar Mar 20 '21 at 20:24
  • 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. – Hexaly Mar 22 '21 at 10:33
2
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)
xd y
  • 1,186
  • 3
  • 9